This question already has an answer here:
python: NameError:global name '...‘ is not defined [duplicate]
(1 answer)
Closed 5 years ago.
I want to define a function sumOfLeftLeaves recursively:
class Node(object):
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumOfLeftLeaves(self,root):
if root.val == None:
return 0
elif (root.left.left == None and root.left.right == None):
return root.left.val + sumOfLeftLeaves(root.right)
else:
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right)
But it gives an error "NameError: global name 'sumOfLeftLeaves' is not defined", but I think it's defined recursively, what's wrong?
sumOfLeftLeaves is still a method on the class and not a globally defined function. You can access it as bound method on self, just like you'd access any other method:
self.sumOfLeftLeaves(...)
You should really use is None when testing for the None object as well:
class Solution(object):
def sumOfLeftLeaves(self, root):
if root.val is None:
return 0
elif (root.left.left is None and root.left.right is None):
return root.left.val + self.sumOfLeftLeaves(root.right)
else:
return (self.sumOfLeftLeaves(root.left) +
self.sumOfLeftLeaves(root.right))
Related
This question already has answers here:
Python min function with a list of objects
(4 answers)
Closed 1 year ago.
I have the following class:
class Node:
def __init__(self, node, value, left=None, right=None):
self.node = node
self.value = value
self.left = left
self.right = right
self.code = ''
I have a list of Node. The question is, how can I extract the node with the lowest self.value attribute?
You could use the built-in min function with an anonymous function to access value parameter:
min(listNodes, key=lambda x: x.value)
Or you can define the rich comparison methods __lt__ and __eq__ in Node (you can define additional rich comparison methods, but these two are sufficient for ordering like min):
class Node:def __init__(self, node, value, left=None, right=None):
self.node = node
self.value = value
self.left = left
self.right = right
self.code = ''
def __iter__(self):
return self
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
which will allow min to directly compare the nodes finding the minimum!
min(listNodes)
Before Python3, it was possible to use the now-deprecated __cmp__ method to create all the rich comparison methods at once; see Question About This and Linked Official Notes
This question already has answers here:
Assign class boolean value in Python
(2 answers)
Defining "boolness" of a class in python
(3 answers)
Closed 2 years ago.
I have defined a class in Python 3 and have a case that I create an "empty" class object. Therefor I want to be able to check if the object is empty or not, like you can write:
test = []
if not test:
print('False')
My code for the class looks like this (note that I will accept an empty value for name):
class myClass:
def __init__(self, name=False):
self.name = name
def __str__(self):
return self.name.replace('\n', ' ')
def __repr__(self):
return self.name.replace('\n', ' ')
def __eq__(self, other):
if not isinstance(other, myClass):
return False
if not self.name and not other.name:
pass
elif not (self.name or other.name):
return False
elif self.name != other.name:
return False
return True
Now I would like to check if I got an empty class:
test = myClass()
if not test:
print('False')
else:
print('True')
The result of this case will always be true. How can I change this behaviour?
Add a __bool__ method to your class:
def __bool__(self):
return bool(self.name)
To cater for the case where self.name == '' and you want to return True:
def __bool__(self):
return self.name is not False
This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 3 years ago.
can anybody explain why it is showing me and how to print it?
what am I doing wrong and how to print this object reference?
i have also tried printing new_list(inside sort() ) but still the same
I am printing list then why it is not showing
I know some of the people asked before about related to this...but still I didn't get it.
class node(object):
def __init__(self, d, n=None):
self.data=d
self.next_node=n
def get_data(self):
return self.data
def set_data(self,d):
self.data=d
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node=n
def has_next(self):
if self.get_next() is not None:
return True
else:
False
class LinkedList(object):
def __init__(self, r=None):
self.root=r
self.size=0
def get_size(self):
return self.size
def add(self,d):
new_node = node(d, self.root)
self.root = new_node
self.size+=1
def sort(self):
if self.size>2:
newlist = []
this_node = self.root
newlist.append(this_node)
while this_node.has_next():
this_node = this_node.get_next()
newlist.append(this_node)
newlist = sorted(newlist ,key = lambda node: node.data,reverse=True)
newLinkedList = LinkedList()
for element in newlist:
newLinkedList.add(element)
return newLinkedList
return self
new_list=LinkedList()
new_list.add(10)
new_list.add(20)
new_list.add(30)
new_list.sort()
i expected that it will print list print a list
but it is showing <main.LinkedList object at 0x00E20BB0>
how to print this object ?
You are not printing out node values of the linked list instead you are printing out the return value of the sort() function which is an object of the class LinkedList.
If you want to print the linked list, you have to traverse the list and print out each node value individually.
Here is the recursive solution of how you can print a linked list.
def print_list(head):
if head != null:
print(head.val)
print_list(head.next)
You can call this method after calling the sort function
I am trying to traverse a tree but getting above error. Please help me out. I am trying to call a definition of same class and as parameter sending a class object. But calling definition not able to identify type of parameters.
Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def same(self, s, t):
if(s is None and t is None):
return True
if(s is None or t is None):
return False
return s.val==t.val and self.same(s.left,t.left) and self.same(s.right,t.right)
def traverse(self, s, t):
return (s!="" and (self.same(s,t) or self.traverse(s.left,t) or self.traverse(s.right,t)))
def isSubtree(self, s, t):
# print s.val
return self.traverse(s,t)
The problem looks like it is the '' check as opposed to a None check in traverse. It will pass None values to same because of this.
Assuming that t and s are TreeNode objects, where do you declare them? Is it possible that you're passing undeclared variables to Solution?
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
class Node:
def __init__(self, v):
self.l = None
self.r = None
self.v = v
class BinaryTree:
def __init__(self):
self.root = None
def put(self, v):
if self.root is None:
self.root = Node(v)
else:
if self.root is None:
self.root = Node(v)
elif self.root.v <= v:
self.root.r = self.put(self.root.r, v)
elif self.root.v > v:
self.root.l = self.put(self.root.l, v)
return self.root
def __contains__(self, v):
return finns(self.root, v)
def write(self):
if self.root is not None:
print(self.root.v)
if self.root.l is not None:
self.write(self.root.l)
if self.root.r is not None:
self.write(self.root.r)
a = BinaryTree()
a.put(3)
a.put(4)
a.write()
I wonder why it doesn't work. It says:
TypeError: put() takes 2 positional arguments but 3 were given
I just want to use put() to input integers in the tree.
(Note: "V" stands for value. "R" for right and "L" for left.)
You're getting the TypeError because you're using put() incorrectly. However the real problem is you're not building the tree properly.
In the code below that problem is fixed plus I also corrected the write() __contains__() methods both of which also had.
class Node:
def __init__(self, v):
self.l = None
self.r = None
self.v = v
class BinaryTree:
def __init__(self):
self.root = None
def put(self, v):
if self.root:
self._put(v, self.root)
else:
self.root = Node(v)
def _put(self, v, node):
if v < node.v:
if node.l:
self._put(v, node.l)
else:
node.l = Node(v)
else:
if node.r:
self._put(v, node.r)
else:
node.r = Node(v)
def __contains__(self, v):
return (False if not self.root
else self._find(v, self.root) is not None)
def _find(self, v, node):
if v == node.v:
return node
elif v < node.v and node.l is not None:
return self._find(v, node.l)
elif v > node.v and node.r is not None:
return self._find(v, node.r)
def write(self):
if self.root is not None:
self._write(self.root, 0)
def _write(self, node, level):
if node is not None:
self._write(node.l, level+1)
print(' '*level + str(node.v))
self._write(node.r, level+1)
a = BinaryTree()
a.put(3)
a.put(4)
a.put(5)
a.put(9)
a.put(7)
a.put(10)
a.write()
print('')
print('{:2} in "a" -> {}'.format(5, 5 in a))
print('{:2} in "a" -> {}'.format(42, 42 in a))
Output:
3
4
5
7
9
10
5 in "a" -> True
42 in "a" -> False
In the line self.root.r = self.put(self.root.r, v) you call the instance method put with two explicit arguments. Since you are calling the method on self, the method is bound and self is passed implicitly as the first argument (for three arguments total).
Your code doesn't currently make enough sense for me to offer an easy fix. For example, you could pass an instance explicitly to BinaryTree.put, but you're currently trying to pass an instance of Node not BinaryTree.