'None' in python -


i have simple program above creates bst sorted array. should parse tree without showing leaves none. explain why program still spits out 'none'. i'm python noob , appreciate help.i have tried != 'none' along none same results.

class node:     def __init__(self,value):         self.value=value         self.nodeleft=none         self.noderight=none  def makebst(ia,start,end,tree):     if (end < start):         return none     mid = (start + end) / 2     n = node(ia[mid])     n.nodeleft = makebst(ia, start, mid-1, tree)     n.noderight = makebst(ia, mid+1, end, tree)     tree.append(n)     return n  def printbst(root):     print 'rr' ,root.value     if root.nodeleft == none:         print 'eot'     else:             print printbst(root.nodeleft)      if root.noderight == none:         print 'eot'     else:             print printbst(root.noderight)  if __name__ == '__main__':     array = [1, 2, 3, 4, 5, 6]     dic = []     root = makebst(array, 0, len(array)-1, dic)     printbst(root) 

the problem code passing return value of printbst print. since printbst not return anything, none printed.

so when wrote:

print printbst(root.nodeleft) 

that code print none because printbst not contain return statement , defaults returning none.

you need change printbst this:

def printbst(root):     print 'rr' ,root.value     if root.nodeleft none:         print 'eot'     else:             printbst(root.nodeleft)      if root.noderight none:         print 'eot'     else:             printbst(root.noderight) 

note using is correct way test none.

that said, can make code simpler this:

def printbst(root):     if root none:         print 'eot'         return     print 'rr', root.value     printbst(root.nodeleft)     printbst(root.noderight) 

as being simpler, code has additional benefit of not failing when presented empty tree.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -