1

I'm trying to update either the variable one or two from inside the calc function and then print it in the rob function. But whenever I do it, its reverted back to zero and thats causing problems

Used the global keyword as mentioned Using global variables in a function and can't access global variable from inside a function in python but that doesnt seemed to work

class Solution(object):
    one=0
    two= 0
    def calc(self,root,flag):
        global one
        global two
        if root == None:
            return
        if flag:
            self.one+=root.val
            Solution().calc(root.left,False)
            Solution().calc(root.right, False)
        else :
            self.two+=root.val
            Solution().calc(root.left, True)
            Solution().calc(root.right, True)
        print (str(root.val)+" " + str(self.one) + " " + str(self.two))
    def rob(self, root):
        self.calc(root,True)
        global one
        global two        
        print self.one
        print self.two
        return max(self.one,self.two)

Its basically​ always reverting one and two back to zero

orde
  • 5,233
  • 6
  • 31
  • 33
coder
  • 119
  • 1
  • 2
  • 10

1 Answers1

0

Without the definition of root and a sample invocation of code that is giving the incorrect answer it's hard to answer your question. That said, I think that the issue is that you're asigning root.val to a Solution attribute not incrementing the globals:

# You have:
self.one += root.val
# You want:
one += root.val
it's-yer-boy-chet
  • 1,917
  • 2
  • 12
  • 21