Recursive algorithms anyone?

Kirby Urner urner at alumni.princeton.edu
Thu Jun 7 01:18:12 EDT 2001


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