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

1
  • Why are you using a class that doesn't us any internal state and tried to use global variables? That defeats the entire purpose of a class Commented Jun 5, 2019 at 0:46

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.