Extract min value node [duplicate] - python

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

Related

Calculating no. of nodes in a Binary Tree in O(1)?

I am taking Data Structures and Algorithm course from Jovian. Currently on Binary Tress, but I am stuck on one question where we need to calculate no. of nodes in O(1) time.
Firstly here's how the final class TreeMap looks like:
class TreeMap:
def __init__(self):
self.root = None
def __setitem__(self, key, value):
node = find(self.root, key)
if not node:
self.root = insert(self.root, key, value)
self.root = balance_tree(self.root)
else:
update(self.root, key, value)
def __getitem__(self, key):
node = find(self.root, key)
return node.value if node else None
def __iter__(self):
return (x for x in list_all(self.root))
def __len__(self):
return size(self.root)
def display(self):
return display_keys(self.root):
Currently, it's calculating no. of nodes with the recursion method. I think we just need a counter and increment every time a node is created and we also have a hint to modify the BSTNode class. So this is how I did it:
class BSTNode:
counter = 0
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = None
BSTNode.counter += 1
But I don't know how do I implement or use the counter in __len__ function in class TreeMap. Any help would be much appreciated.
Here is the link to Jovian Lesson: https://jovian.ai/learn/data-structures-and-algorithms-in-python/lesson/lesson-2-binary-search-trees-traversals-and-balancing

tree.put(key, value) insertion

So I'm working on an assignment for a data structures class, and one question is to create a put(key, value) method for an AVLTree. I know I have to adding the balancing method, but right now I'm just on the actual insertion. I want the function to work where you can create a tree and type newTree.put(key value) and have it work. Right now I have
class node:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
self.height = 0
class AVLTreeMap:
def __init__(self, key, value):
self.root = node(key, value)
#inserting new key-value pair, NEED TO ADD BALANCING ABILITY
def put(self, key, value, height=0):
if(key < self.root.key):
if(self.root.left == None):
self.root.left = node(key, value)
self.root.left.height = height+1
else:
self.root = self.root.left
self.put(key, value, height+1)
else:
if(self.root.right == None):
self.root.right = node(key, value)
self.root.right.height = height+1
else:
self.root = self.root.right
self.put(key, value, height+1)
However, the recursive aspect of put just discounts the root, and creates a new tree of just one parent and that node as one child. Is this the right way to go about this, or is there an easier way? Also, if I do it this way, how do you recurse left and right in this method?

How to define function in class properly in Python? [duplicate]

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))

Create python functions from expression trees

I'm trying to create collection filters from expression trees (these would be generated from the GUI using wxpython tree controls). I would then use these filters with python's filter(func, iterable) method.
The challenge now is how can I create a function at runtime based on the rules found in the expression tree. An example of how such a function would look is:
def filterFunc(element):
if element == 'Apple' or element == 'Orange' or element == 'Duck':
return True
return False
The solution I'm currently thinking is to traverse the tree, generate a string containing actual Python code based on the tree contents(probably painful to code), and then call eval() on the resulting string.
Any advice or pointers on what would the correct/pythonic way to solve this would be much appreciated !
I'm assuming that your expression tree is composed of a number of objects, whose type corresponds with what kind of expression it is. Ex. Or, Equals, strings, etc. Something like this:
class OrExpression:
def __init__(self, left, right):
self.left = left
self.right = right
class EqualsExpression:
def __init__(self, left, right):
self.left = left
self.right = right
class Literal:
def __init__(self, value):
self.value = value
class Variable:
def __init__(self, name):
self.name = name
An expression equivalent to your example would look like this:
e = OrExpression(
EqualsExpression(
Variable("element"),
Literal("Apple")
),
OrExpression(
EqualsExpression(
Variable("element"),
Literal("Orange")
),
EqualsExpression(
Variable("element"),
Literal("Duck")
)
)
)
You could create a method eval for each class that evaluates itself for a given context. Like so:
class OrExpression:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self, variables):
return self.left.eval(variables) or self.right.eval(variables)
class EqualsExpression:
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self, variables):
return self.left.eval(variables) == self.right.eval(variables)
class Literal:
def __init__(self, value):
self.value = value
def eval(self, variables):
return self.value
class Variable:
def __init__(self, name):
self.name = name
def eval(self, variables):
return variables[self.name]
Then you can call eval and supply the context. In your example, you only need to pass in the value of element.
print e.eval({"element": "Apple"})
print e.eval({"element": "Duck"})
print e.eval({"element": "Banana"})
Result:
True
True
False
But what if, instead, you don't differentiate kinds of expression by type? Suppose your tree is composed of plain old nodes, that identify what kind of expression they are using their value attribute. The code is approximately the same, just using a single monolithic switch case, instead of individual eval methods.
class Node:
def __init__(self, value=None, *children):
self.value = value
self.children = children
def evalTree(t, variables):
if t.value == "Or":
return evalTree(t.children[0], variables) or evalTree(t.children[1], variables)
elif t.value == "Equals":
return evalTree(t.children[0], variables) == evalTree(t.children[1], variables)
elif t.value == "Literal":
return t.children[0].value
elif t.value == "Variable":
name = t.children[0].value
else:
raise Exception("Unrecognized node type")
t = Node("Or",
Node("Equals",
Node("Variable", Node("element")),
Node("Literal", Node("Apple"))
),
Node("Or",
Node("Equals",
Node("Variable", Node("element")),
Node("Literal", Node("Apple"))
),
Node("Equals",
Node("Variable", Node("element")),
Node("Literal", Node("Apple"))
)
)
)
print evalTree(t,{"element": "Apple"})
print evalTree(t,{"element": "Duck"})
print evalTree(t,{"element": "Banana"})
Result:
True
True
False

Python object instantiation

I am very new to python and need some help with instantiating an object. The python interpreter is giving me trouble when instantiating an object of a class I defined. There are two classes, BTNode and BST (which are stored in files bst_node.py and bst.py respectively):
# file: bst_node.py
class BTNode:
"""a binary search tree node implementation"""
def ___init___(self, value):
self.value = value
self.left is None
self.right is None
self.parent is None
def ___init___(self, value, left, right, parent):
"""set the parameters to corresponding class members"""
self.value = value
self.left = left
self.right = right
self.parent = parent
def is_leaf(self):
"""check whether this node is a leaf"""
if self.left.value is None and self.right.value is None:
return True
return False
# file: bst.py
from bst_node import *
class BST:
"""a binary search tree implementation"""
def ___init___(self, value):
self.root = BTNode(value)
def insert(self, curRoot, newValue):
if curRoot.is_leaf():
if newValue < curRoot.value:
newNode = BTNode(newValue, None, None, curRoot)
curRoot.left = newNode
else:
newNode = BTNode(newValue, None, None, curRoot)
curRoot.right = newNode
else:
if newValue < curRoot.value:
self.insert(curRoot.left, newValue)
else:
self.insert(curRoot.right, newValue)
So, in the interpreter I do:
import bst as b
t1 = b.BST(8)
and I get an error which says that this constructor takes no arguments
The constructor clearly takes an argument value so what is going wrong here? How can I fix this error?
Thanks, all help is greatly appreciated!
The first issue is that you called your functions ___init___ instead of __init__. All of the 'special methods' use two underscores.
A second issue in this code is that in BTNode you redefined __init__. You can't overload functions in python. When you reclare __init__ you effectively deleted the first constructor.
A third issue is your usage of is. is is an operator that checks whether two objects are exactly the same and returns True or False. In the constructor, you have a few self.left is None is examining the value of self.left (which wasn't declared yet), and examining whether or not it is None. To set it, use = as follows:self.left = None
To fix the second and third issue you should use default argument values. For example:
def __init__(self, value, left=None, right=None, parent=None):
In addition to the number of underscores problem, you should replace
def ___init___(self, value):
self.value = value
self.left is None
self.right is None
self.parent is None
def ___init___(self, value, left, right, parent):
"""set the parameters to corresponding class members"""
self.value = value
self.left = left
self.right = right
self.parent = parent
with
def __init__(self, value, left=None, right=None, parent=None):
"""set the parameters to corresponding class members"""
self.value = value
self.left = left
self.right = right
self.parent = parent
Because as #Moshe points out, you can't overload functions, you should use default arguments insted.
Changing ___init___ to __init__ should fix it. (2 underscores vs 3)

Categories