Defining a global variable inside a class vs. defining inside a method - python-3.x

I am trying to find the vertical width if a binary tree as defined in this link; https://practice.geeksforgeeks.org/batch/dsa-4/track/DSASP-Tree/problem/vertical-width-of-a-binary-tree
My question is regarding defining a global variable inside a class vs defining it inside a method. Here is my code, which is working as expected in the present form;
class Node:
#global dnew
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def vertical_width(self):
#dnew = {self.data: 0}
#print(self.data, dnew)
if self is None:
return
# if we move left decrease value by 1
if self.left != None:
dnew[self.left.data] = dnew[self.data] - 1
self.left.vertical_width()
print('left', dnew)
# if we move right increase value by 1
if self.right != None:
dnew[self.right.data] = dnew[self.data] + 1
self.right.vertical_width()
print('right', dnew)
return dnew
def mainfn(self):
global dnew
dnew = {self.data:0}
result = self.vertical_width()
return len(set(result.values()))
class Tree:
def __init__(self,root):
self.root = root
# define a tree as an example to test the code
node = Node(1)
node.left = Node(2)
node.left.left = Node(3)
node.left.right = Node(4)
node.right = Node(5)
#node.right.left = Node(6)
mytree = Tree(node)
res = mytree.root.mainfn()
Question is, if we just define global dnew inside the Node class rather than defining it inside the mainfn(), we get following error message;
NameError: name 'dnew' is not defined
But isn't that if we define a variable with global keyword, it shd be accessible by all methods in a class.Can I please get some help to understand this concept?

Related

Wrapper Class in Python for Linked List

I am absolutely new to Wrapper Classes in Python. I was trying to implement it in a program of linked list where multiple linked list are in use. My code is:
def nodewrap(cls):
class Nodewrap:
def __init__(self):
self.head = None
self.tail = None
return Nodewrap
#nodewrap
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Intersection:
def addnode(self,d):
newnode = Node(d)
if head == None:
head = tail = newnode
else:
tail.next = newnode
tail = newnode
obj1 = Intersection()
obj2 = Intersection()
obj3 = Intersection()
s1 = int(input("Enter size of 1st list : \n"))
for i in range(s1):
obj1.addnode(int(input("Enter the data : \n")))
s2 = int(input("Enter size of 1st list : \n"))
for i in range(s2):
obj2.addnode(int(input("Enter the data : \n")))
temp1 = obj1.head
for i in range(s1):
temp2 = obj2.head
for j in range(s2):
if temp1.data == temp2.data:
obj3.addnode(temp1.data)
break
temp2 = temp2.next
temp1 = temp1.next
print("Intersection is :")
temp = obj3.head
while temp!=None:
print(temp.data,end=" ")
temp = temp.next
I thought of using a wrapper class to wrap the class Node instead of using objects of the class Intersection only with data fields as head, tail. But it is giving me some sort of error with regards to init().
Please help.
I was trying to learn it from here:
https://www.geeksforgeeks.org/wrapper-class-in-python/
I think I understand what you want to do, but I think that you don't want to use a decorator, but you want to inherit from NodeWrap class
class Nodewrap:
head = None
tail = None
class Node(NodeWrap):
def __init__(self,data):
self.data = data
self.next = None
But I don't see any reason why to inherit this way. This should be enough, for a linked list. I have added is_first and is_last property
from __future__ import annotations
class Node:
prev_node = None
next_node = None
def __init__(self, data):
self.data = data
def add_node(self, node: Node) -> None:
if self.prev_node is not None:
raise ValueError('Previous node already defined.')
self.next_node = node
node.prev_node = self
#property
def is_first(self) -> bool:
return self.prev_node is None
#property
def is_last(self) -> bool:
return self.next_node is None
You can implement next, iter and create an Iterator class.
I don't recommend using next as the variable name.
from __future__ import annotations reference here. It's just for self reference annotation.

Traversal of a binary tree: i cannot get right output in python

I am typing pre-order traversal and the output is just '1-'; I have looked through several other threads on this site but cannot seem to find my mistake. Any hints or suggestions would be appreciated!
class Node(object):
def __init__(self, value):
self.number = value
self.left = None
self.right = None
class binarytree(object):
def __init__(self, root):
self.root = Node(root)
def print_traversal(self, direction, start):
if direction == 'pre_order':
return self.pre_order(start, '')
def pre_order(self, start, traversal):
if start:
traversal += (str(start.number) + '-' )
self.pre_order(start.left, traversal)
self.pre_order(start.right, traversal)
return traversal
# main function
tree1 = binarytree(1)
tree1.root.left = Node(2)
tree1.root.right = Node(3)
tree1.root.left.left = Node(4)
tree1.root.left.right = Node(5)
tree1.root.right.left = Node(6)
print(tree1.print_traversal('pre_order', tree1.root))```
The line
traversal += (str(start.number) + '-' )
assigns a new value to the local variable traversal; it does not modify the string already in traversal. Thus, the changes made in the recursive calls are never seen at the level above where they're made.

How to define and use a funciton outside a class?

In the following code for linked list implementation in Python3. How do I define and call the functions such as reverse() and display() outside of the class. Like, how should create a function that performs operations like display() and recerse(). How should I pass a LinkedList object and how to access its members, so that I am able to do desired operations?
PS : I removed other functions because I was not able to post this question.
I am not asking about importing the class file to use in other .py files.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
curr = self.head
while curr != None:
print(curr.data + '->', end = ' ')
curr = curr.next
print('NULL')
def append(self, data):
'''
statements....
'''
def length(self):
ptr = self.head
count = 0
while ptr.next != None:
count += 1
ptr = ptr.next
print(count+1)
def reverse(self):
pre = None
cur = self.head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
self.head = pre
self.display()
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()
not sure I'm understanding your question correctly, but if I am it seems that you just want to take all of the code, minus the program code (from "l=LinkedList()" down in your example), and save it to a python file, then at the top of any python code you need to use your class in, import your file.
If your class file is not in the same directory as the code from which you wish to use the class, you'll need to keep the class file in a directory in your path:
import sys
print(sys.path)
and if you wish to add a directory to your path, you can:
sys.path.append('<directory')
At that point, once you
import LinkedList
(assuming your class file is called LinkedList.py) you'll be able to define variables using your class and use it the same as you would in your example, so your code file would look something like:
import LinkedList
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()
Or am I just not reading your question correctly?
I added the prepend and append method for you, I'm not sure if this is what you were referring to. Also, if you're looking for static vs class methods, you can check those out here: Class method vs static method in Python
With static methods you can return instances of a specified class by using arguments to the static method. Check out the link above to use class functions outside of their instances.
Here is the Python code:
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
curr = self.head
while curr != None:
print(curr.data + '->', end = ' ')
curr = curr.next
print('NULL')
def append(self, data):
data_node = Node(data)
data_node.next = self.head
self.head = data_node
def prepend(self, data):
ptr = self.head
while ptr.next != None:
ptr = ptr.next
ptr.next = Node(data)
def length(self):
ptr = self.head
count = 0
while ptr.next != None:
count += 1
ptr = ptr.next
print(count+1)
def reverse(self):
pre = None
cur = self.head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
self.head = pre
self.display()
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.prepend('E')
l.display()

Binary Tree implementation with Separate class for node and tree

I am new to Python and data structures. While learning binary tree, I found all the available implementations have the methods of the tree inside the node class.
But I want to implement it differently, where along with the Node class, there will be a Binary tree class, which will contain the methods of the Binary tree.
This is the code I came up with, but it raises an error with the arguments I am passing to the functions insertleft() and insertright().
class Node():
def __init__(self, arg):
self.left = None
self.right = None
self.data = arg
class Bt():
def __init__(self, root):
self.root = root
def insertleft(temp.left, data):
if (temp.left == None):
temp.left.data = data
elif(data<temp.left.data):
t1 = temp.left
insertleft(t1.left, data)
elif(data>temp.left.data):
t1 = temp.left
insertright(t1.left, data)
def insertright(temp.right, data):
if (temp.right == None):
temp.right.data = data
elif(data<temp.right.data):
t1 = temp.right
insertleft(t1.right, data)
elif(data>temp.right.data):
t1 = temp.right
insertright(t1.right, data)
def insert(self, data):
temp = self.root
if(temp.data = None):
temp.data = data
elif(data<temp.data):
insertleft(temp.left, data)
elif(data>temp.data):
insertright(temp.right, data)
r = Bt()
r.root = Node(5)
r.insert(4)
r.insert(6)
These is the error I received:
def insertleft(temp.left, data):
^
SyntaxError: invalid syntax
I am not sure what the right syntax should be. Thanks in advance for your help
When you define a function, you also define the parameters you will be accepting. Inside a class though, as long as the method is not static or a class method, the first parameter should be self or a variable that represents the instanciated object itself.
In your case, you are already passing the value of temp.left and temp.right when calling the function. Changing the function definitions to just use temp should work just fine. Or even more readible, node since that is what you are actually referring to.
Your insertleft and insertright functions do the same thing as insert, and including them is not necessary. Just modify the insert function to do it all.
Here's what the end result should resemble:
class Node():
def __init__(self, arg):
self.left = None
self.right = None
self.data = arg
class Bt():
def __init__(self, root=None): #Added default value
self.root = Node(root)
def insert(self, data):
if self.root.data is None:
self.root.data = data #Set the root data if it doesn't exist.
else:
self._insert(self.root, data) #Prime the helper function with root node
def _insert(self, node, data): #Insert helper function to do the insertion
if data < node.data: #Check if data needs to be inserted on the left
if node.left is None: #Set left node if it doesn't exist
node.left = Node(data)
else: #Else let the left node decide where it goes as a child
self._insert(node.left, data)
else: #Else data needs to be inserted on the right
if node.right is None: #Set right node if it doesn't exist
node.right = Node(data)
else: #Else let the right node decide where it goes as a child
self._insert(node.right, data)
r = Bt(5)
r.insert(4)
r.insert(6)
Now you're just missing functions to print the Tree and Data... and accessing the data.
Each Node in the binary search tree is considered as a another binary search tree. Hence we don't need to create a separate class for node.

binary search tree - recursive insertion python

I'm trying to correctly construct a binary search tree with a recursive insert function that will allow me to initialize a tree and continue to add nodes (stems). Here is the code that I've done so far (newer to coding, so probably way too wordy):
class Binary_Search_Tree:
class __BST_Node:
def __init__(self, value):
self.value = value
self.right_child = None
self.left_child = None
def __init__(self):
self.__root = None
self.__height = 0
self.value = None
def _recursive_insert(self, value):
new_stem = Binary_Search_Tree.__BST_Node(value)
if self.__root is None:
self.__root = new_stem
self.__root.value = new_stem.value
else:
if self.__root.value > new_stem.value:
if self.__root.right_child is None:
self.__root.right_child = new_stem
self.__root.right_child.value = new_stem.value
else:
self.__root.right_child._recursive_insert(self.__root, value)
else:
if self.__root.left_child is None:
self.__root.left_child = new_stem
self.__root.left_child.value = new_stem.value
else:
self.__root.left_child._recursive_insert(self.__root, value)
def insert_element(self, value):
element_to_insert = self._recursive_insert(value)
return element_to_insert
I then try to add values to this new tree in the main method:
if __name__ == '__main__':
new = Binary_Search_Tree()
new.insert_element(23)
new.insert_element(42)
new.insert_element(8)
new.insert_element(15)
new.insert_element(4)
new.insert_element(16)
The error that I keep getting is: '__BST_Node' object has no attribute '_recursive_insert' This pops up after inserting the first element, so I'm guessing the error occurs somewhere in the else statement. If anyone can figure out where my error is or has any tips on how to make this code more readable/user friendly, I'd be appreciative!
The issue is with this line:
self.__root.right_child._recursive_insert(self.__root, value)
As well as this:
self.__root.left_child._recursive_insert(self.__root, value)
You've defined _recursive_insert to be a method of Binary_Search_Tree, but you're calling it with an instance of __BST_Node, in self.__root.xxxxx_child._recursive_insert, where xxxx_child is an instance of BST_Node.
In fact, your entire _recursive_insert function leaves something to be desired. You're not returning anything from it, but you are assigning it's (non-existent) return value to something in insert_element.
Fixed code:
def _recursive_insert(self, root, value):
new_stem = Binary_Search_Tree.__BST_Node(value)
if root is None:
root = new_stem
else:
if root.value < new_stem.value:
if root.right_child is None:
root.right_child = new_stem
else:
root = self._recursive_insert(root.right_child, value)
elif root.value > new_stem.value:
if root.left_child is None:
root.left_child = new_stem
else:
root = self._recursive_insert(root.left_child, value)
return root
def insert_element(self, value):
self.__root = self._recursive_insert(self.__root, value)
return element_to_insert
Your function did not return an updated root
Your function does not handle a case when the value being inserted would be equal to an existing value, causing spurious entries.
With each recursive call, your function was being passed the same values, so it would not be able to know what to do. A new parameter for the node must be passed across calls. This makes it possible to establish a base case and return.

Resources