Recursive algorithms anyone?

eric jones ej at ee.duke.edu
Thu Jun 7 07:38:03 CEST 2001


Here is an alternative approach:

def add_item(val,lst):
    new_lst = []
    for item in lst:
        if type(item) is type([]):
            new_lst.append(add_item(val,item))
        else:
            new_lst.append(item + val)
    return new_lst

print add_item(1,[1,2,[3,4,[5,6]],7])
[2, 3, [4, 5, [6, 7]], 8]

"Kirby Urner" <urner at alumni.princeton.edu> wrote in message
news:1f0uhtgmhb0vlud6pof6i4mctqjdq8l2eu at 4ax.com...
>
>
> 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
>
> CC pdx4d at teleport.com por favor
>





More information about the Python-list mailing list