On Feb 8, 7:20 pm, "Zack" <[EMAIL PROTECTED]> wrote: > Hi all. I'm just starting to pick up python. I wanted to play with nested > lists so first I wrote a little bit of code to create arbitrarily nested > lists (grow). Then I wrote a breadth first search. I'm putting this small > snippet up asking for criticism. Was there a more elegant way to do what I'm > doing? Anything that goes against convention? Anything that fingers me as a > c++ programmer? Are there standard modules that do these kind of things? > Thanks for any feedback. > > ############################## > from random import randint > > Val = 0 > > def grow(L,depth): > '''grows L by appending integers and arbitrarily nested lists with a > maximum > depth. Returns L.''' > global Val > if depth == 0: > return L > else: > choice = randint(1,2) > if 1 == choice: > # add a numerical literal > Val += 1 > L.append(Val) > return grow(L,depth-1) > elif 2 == choice: > # add a list > L.append( grow([],depth-1) ) > return grow(L,depth-1)
How about: from itertools import count from random import randrange def grow(L, depth, counter=count()): '''grow L by appending integers and arbitrarily nested lists with a maximum depth. Returns L.''' if depth == 0: return L else: L.append(counter.next() if randrange(2) else grow([], depth-1)) return grow(L, depth-1) > def traverse(L, count=0): > '''Prints the non iterable object of L in breadth first order. > Returns count + the number of non iterables in L.''' > if L == []: > return count > n = [] > for e in L: > if not hasattr(e,'__iter__'): > print e, > count += 1 > else: > n[:] += e I would write n.extend(e) here (or n += e) > print '\n' > return traverse(n,count) > > L = grow([],10) > C = traverse(L) > ############################## > > -- > Zack -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list