Recursive algorithms anyone?
Chad Everett
chat at linuxsupreme.homeip.net
Thu Jun 7 13:59:33 EDT 2001
On Wed, 06 Jun 2001 22:18:12 -0700, Kirby Urner <urner at alumni.princeton.edu> wrote:
>
>
>How to implement in Python the classic thing of
>adding k to every item in a list. Except a list
>may contain other lists to arbitary depth?
>
>I say classic because it's the kind of thing you
>do in computer science 101.
>
>E.g. >>> additem(1,[1,2,[3,4,[5,6]],7])
> [2,3,[4,5,[6,7]],8]
>
>Here's the Scheme solution:
>
>(define (additem items k)
> (cond ((null? items) null)
> ((not (pair? items)) (+ items k))
> (else (cons (additem (car items) k)
> (additem (cdr items) k)))))
>
>
>My best Python attempt so far:
>
> >>> def additem(items, k):
> if not type(items) == type([]): return items + k
> if len(items)==0: return []
> return [additem(items[0],k)] + additem(items[1:],k)
>
> >>> additem([[9,8],1,2,3,4,[1,2, [5,6]]],1)
> [[10, 9], 2, 3, 4, 5, [2, 3, [6, 7]]]
>
>But maybe there's a better solution?
>
>Kirby
>
I don't think this is "better", but I think it's more readable:
def addcomp(L,num):
if type(L) != type([]): return L+num
if L == []: return L
return [addcomp(L[0],num)] + addcomp(L[1:],num)
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 80,000 Newsgroups - 16 Different Servers! =-----
More information about the Python-list
mailing list