Critique of first python code

Zack goldsz at gmail.com
Fri Feb 8 20:20:37 CET 2008


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)
      
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         
   print '\n'
   return traverse(n,count)
   
L = grow([],10)
C = traverse(L)
##############################


--
Zack




More information about the Python-list mailing list