tags:

views:

193

answers:

4

I wanted to create a simple binary tree as followed by this image:

http://imgur.com/QCVSW.png

basically empty , but the last values so I created the root list :

root = [list(),list()]

and made a recursive function to populate it all :

def TF(nodeT,nodeF , i):
    if i == 35 : return 'done'

    TF(nodeT.append([]),nodeT.append([]) , i = i + 1) #append T , F in the true node
    TF(nodeF.append([]),nodeT.append([]) , i = i + 1) #append T , F in the false node

my problem is simple list.append(something) in python return "None" so as soon as the function get called again (TF(None,None,1)) None.append doesnt exists.

how do I solve this? thanks in advance.

also if you have any suggestion on how to make this more efficient or in another way (never got to test my code so I am not sure on how it will do)

(my final goal is to have a True False map and an argument so : "FTFTFFFTFTF" will bring up the letter "M" etc ...)

+4  A: 

To solve your exact question, you can do this:

def list_append(lst, item):
  lst.append(item)
  return lst

and then list_append(lst, item) will append item to the lst and then return the lst.

Peter
+1 Probably does not get better than this
Hamish Grubijan
+2  A: 

You can append first and then pass the reference:

nodeT.append([])
TF(nodeT, nodeT, i + 1)

But your function makes no sense to me. Even if it did make sense, it would cause 2**35 function calls to TF, which would take rather a long time to complete.

Mark Byers
+1  A: 

There's a better way to create a binary tree, but I could not understand what you want to do with it.

Here is the code:

>>> def tree(i):
    if i == 0:
     return ['T', 'F']
    return [tree(i-1), tree(i-1)]

>>> tree(3)
[[[['T', 'F'], ['T', 'F']], [['T', 'F'], ['T', 'F']]], [[['T', 'F'], ['T', 'F']], [['T', 'F'], ['T', 'F']]]]
jbochi
+2  A: 

Dont append to the list, create them. Python has custom data structures btw :P

class BinTree(object):
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right
    def __str__(self):
        return " (%s, %s) " % (self.left, self.right)

def maketree( depth ):
    if depth == 0:
     return BinTree( True, False )
    return BinTree(
     maketree( depth-1 ),
     maketree( depth-1 ))

print maketree( 4 )

If you really, really want lists then replace BinTree( x, y ) with [x,y]

THC4k