how can i change my print function in Singly linked? - python-3.x

I'm new to data structures in python. i just started them past few weeks. i strucked with some code in python.
here is the code.
class Node:
def __init__(self,value):
self.data=value;
self.next=None;
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(head):
if head is not None:
print(head.data)
display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head;
self.head=temp;
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp;
else:
self.tail.next=temp;
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"));
if n==0:
return;
for i in range(n):
value = int(input("enter element to be inserted"));
self.insert_at_end(value)
list=SinglyLinkedList()
list.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
list.display_List(list.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
list.insert_in_beginning(value);
elif option ==3:
value= int(input("enter element to be inserted: "))
list.insert_at_end(value);
every thing is working fine except display_List function. I want to print the elements using recurssion way. I messed up some where.
but the code snippet is same and i changed the display_List to following function it is working good. i want to change it to recursive way.
def display_List(self):
if self.head is None:
print("List is empty")
return
else:
print("List is:",end=" ");
p=self.head
while p is not None:
print(p.data,end=" ")
p=p.next;
if option == 1:
list.display_List()
this function is working fine insteed of recursive. can someone please help me to correct this code.

You have to call this function with class object.
You defined it befor , here:
Do not use 'list' use other as 'l' , list is keyword.
l=SinglyLinkedList()
Must called function like:
l.display_List(head.next)
So your function will be like this:
class Node:
def __init__(self,value):
self.data=value
self.next=None
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(self,head):
if head is not None:
print(head.data)
l.display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head
self.head=temp
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp
else:
self.tail.next=temp
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"))
if n==0:
return
for i in range(n):
value = int(input("enter element to be inserted"))
self.insert_at_end(value)
l=SinglyLinkedList()
l.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
l.display_List(l.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
l.insert_in_beginning(value)
elif option ==3:
value= int(input("enter element to be inserted: "))
l.insert_at_end(value)
ยด
I tested this code , it work well, without any problem.

Related

Send input from function to class

Python beginner here.
I am having hard time understanding how to get user input from function to use it in one of my class methods
class...
def setFirstStageSpeed(self, s):
s = # FIRST_STAGE_SPEED from main()
self.Speed = s
...
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
...
So as shown above, I am trying to get the input value on FIRST_STAGE_SPEED to the setFirstStageSpeed() method.
Here is a solution.you should creaete a instance of SpaceCraft.that's OOP style.
class SpaceCraft:
def setFirstStageSpeed(self, s):
self.Speed = s
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
# make a instance of SpaceCraft.if you not familiar with OOP(Object-oriented programing).you should study about it
spaceCraft = SpaceCraft()
# then call the instance method.set the first stage speed
spaceCraft.setFirstStageSpeed(FIRST_STAGE_SPEED)

How to fix "None" answer and Take inputs as arguments?

I'm giving mettl exam and the question was for solving the parenthesis are matching or not.But all I'm getting as result is NONE.
I'm not sure how to take the input as argument, please help out:
I've tried changing, it is taking the input if I provide a hard coded one.
'''
# these are the metll instructions
class UserMainCode(object):
#classmethod
def areParenthesisBalanced(cls, input1):
'''
input1 : string
Expected return type : string
'''
# Read only region end
# Write code here
pass
'''
# this is the code I tried
class Stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
def show_me(self):
return self.items
def peek(self):
if not self.is_empty():
return self.items[-1]
input1=[]
def areParenthesisBalanced(input1):
s=Stack()
is_balanced=True
index=0
def is_match(p1,p2):
if p1=="(" and p2==")":
return True
elif p1=="[" and p2=="]":
return True
elif p1=="{" and p2=="}":
return True
else:
return False
while index< len(input1) and is_balanced:
paren=input1[index]
if paren in"({[":
s.push(paren)
else:
if s.is_empty():
is_balanced=False
else:
top = s.pop()
if not is_match(top,paren):
is_balanced=False
index+=1
if s.is_empty() and is_balanced:
return True
else:
return False
print (areParenthesisBalanced(input1))
I was hoping to atleast get a normal True. I'm not sure how to proceed

Trie data structure,Counting the number of words in the trie starting with a particular string given

So this is what i've got till now , i have been trying to implement the trie data structure and
al=list(string.ascii_lowercase)
d={} #for mapping
for i in range(26):
d[al[i]]=i #creating mappings like 'a'=0 ...'z'=25
print(d)
class node:
def __init__(self):
self.children=[0]*26 #0 would indicate ending
self.val=None
class trie:
def __init__(self):
self.root=node()
def insert(self,word):
t=self.root
for i in word:
if t.children[d[i]]!=0:
print('traversing')
t=t.children[d[i]]
else:
#print('here')
t.children[d[i]]=node()
t.children[d[i]].val=i;
t=t.children[d[i]]
def search(self,word):
t=self.root
for i in word:
if t.children[d[i]]!=0:
t=t.children[d[i]]
else:
return 0
return 1
So this is as far as i have been able to implement trie(if any optimizations are there please do mention it :))
Now my question is that if i have ('Stack' , 'Stackoverflow' ,'Stackover' ,'LOL' ) in my trie and i have been given the string 'Stack' so my answer would be 3 occurrences
so for the above case :
-> input : 'Stack'
-> Output : 3
Basically i want to know how many instances of the partial string "Stack" are stored in my Trie
i am having trouble implementing it
import string
al=list(string.ascii_lowercase)
d={} #for mapping
for i in range(26):
d[al[i]]=i
print(d)
class node:
count=0
def __init__(self):
self.children=[0]*26
self.val=None
def increment(self): #this is the change
self.count=self.count+1
def showcount(self):
return(self.count)
class trie:
def __init__(self):
self.root=node()
def insert(self,word):
t=self.root
for i in word:
if t.children[d[i]]!=0:
print('traversing')
t=t.children[d[i]]
t.increment()
else:
#print('here')
t.children[d[i]]=node()
t.children[d[i]].val=i;
print(t.children)
t=t.children[d[i]]
print(t.val)
t.increment()
def search(self,word):
t=self.root
for i in word:
if t.children[d[i]]!=0:
t=t.children[d[i]]
else:
return 0
return(1)
def count(self, word):
t=self.root
for i in word:
if t.children[d[i]] != 0:
t = t.children[d[i]]
else:
return 0
print(t.val)
return(t.showcount())
as pointed out i added count in every node and easily counted it
Thanks for the help !!

Function to Calculate the height of a Binary Search Tree is not working properly

I have tried various methods in order to calculate the height of a Binary Search Tree which includes recursion and also using a list in order to add the node along with it's depth.But for both the methods,the output is not correct.
Here's my code for the same:
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def Insert_BTreeNode(self,data):
if self.data:
if data<=self.data:
if self.left is None:
self.left=Node(data)
else:
self.left.Insert_BTreeNode(data)
elif data>self.data:
if self.right is None:
self.right=Node(data)
else:
self.right.Insert_BTreeNode(data)
else:
self.data=data
def Lookup(self,data,parent=None):
if data<self.data:
if self.left is None:
return None,None
return self.left.Lookup(data,self)
elif data>self.data:
if self.right is None:
return None,None
return self.right.Lookup(data,self)
else:
if (parent is not None):
print(self.data,parent.data)
return (self,parent)
def Children_count(self):
count=0
if self.left:
count+=1
if self.right:
count+=1
return (count)
def Delete(self,data):
children_count=0
node,parent=self.Lookup(data)
if node is not None:
children_count=node.Children_count()
if children_count==0:
if parent:
if parent.left is Node:
parent.left=None
else:
parent.right=None
del node
else:
self.data=data
elif children_count==1:
if node.left:
n=node.left
else:
n=node.right
if parent:
if parent.left is node:
parent.left=n
else:
parent.right=n
del node
else:
self.left=n.left
self.right=n.right
self.data=n.data
else:
parent=node
successor=node.right
while successor.left:
parent=successor
successor=successor.left
node.data=successor.data
if parent.left==successor:
parent.left=successor.right
else:
parent.right=successor.right
def print_treeInorder(self):
if self.left:
self.left.print_treeInorder()
print(self.data)
if self.right:
self.right.print_treeInorder()
def print_treePostorder(self):
if self.left:
self.left.print_treePostorder()
if self.right:
self.right.print_treePostorder()
print(self.data)
def height(self):
if self is None:
return 0
else:
return max(height(self.getLeft()), height(self.getRight()))+ 1
def print_treePreorder(self):
print(self.data)
if self.left:
self.left.print_treePreorder()
if self.right:
self.right.print_treePreorder()
def getLeft(self):
return self.left
def getRight(self):
return self.right
def maxDepth(self): #Level order Traversal
if self is None:
return 1
q=[]
q.append([self,1])
while(len(q))!=0:
node,temp=q.pop()
if node.getLeft()!=None:
q.append([node.getLeft(),temp+1])
if node.getRight()!=None:
q.append([node.getRight(),temp+1])
return temp
b_tree_input=list(map(int,input().split()))
root=Node(b_tree_input[0])
for i in range(1,len(b_tree_input)):
root.Insert_BTreeNode(b_tree_input[i])
print(root.height())
print(root.maxDepth())
For the sample input of 2,1,3,4.Both the function should return the answer as 3 but the height function returns the following.
NameError: name 'height' is not defined
While the maxDepth() function returns the answer as 2.
Regarding height: I'm not a python programmer, but shouldn't it be
max(self.getLeft().height(), self.getRight().height())
// instead of
max(height(self.getLeft()), height(self.getRight()))
since height is a member function?
However, this implies you have to check self.getLeft() and self.getRight() for None values before calling height. If you don't want to do the extra checks, think of making height a global function unrelated to your class, then your previous approach on recursion should work.
The height function with checks for None could look as follows (no guarantee on the syntax details):
def height(self):
if self is None:
return 0
elif self.left and self.right:
return max(self.left.height(), self.right.height()) + 1
elif self.left:
return self.left.height() + 1
elif self.right:
return self.right.height() + 1
else:
return 1
In maxDepth you process child nodes in a right-to-left DFS but you only take the result of the last processed path instead of comparing current temp to the maximum of already found depths.
So in your [2,1,3,4] example, the execution order is as follows:
q=[[2,1]] -> take [2,1] -> temp=1
q=[[1,2],[3,2]] -> take [3,2] -> temp=2
q=[[1,2],[4,3]] -> take [4,3] -> temp=3
q=[[1,2]] -> take [1,2] -> temp=2
end
I think you can now figure out how to change your algorithm.
Also you should consider to change the self is None case to return 0.

Sorting a dictionary that contains a class holding 5 variable by one of the class variables

I have a dictionary that contains keys that are made from a class containing 5 variables. I want to sort this dictionary by one of the class vars.
here is what i currently have
class Player:
def __init__(self,name,wins,losses,ties,winpercent):
self.__name = name
self.__wins = wins
self.__losses = losses
self.__ties = ties
self.__winpercent = winpercent
# mutators
def setname(self,name):
self.__name = name
def setwins(self,wins):
self.__wins = wins
def setlosses(self,losses):
self.__losses = losses
def setties(self,ties):
self.__ties = ties
def setwinpercent(self,winpercent):
self.__winpercent = winpercent
# accessors
def getname(self):
return self.__name
def getwins(self):
return self.__wins
def getlosses(self):
return self.__losses
def getties(self):
return self.__ties
def getwinpercent(self):
return self.__winpercent
def displayHighScores(self):
print("\n"," "*2,self.__name," "*(24-len(self.__name)),self.__wins)
def displayplayers(self):
print(self.__name)
I store Players like this:
def addplayer(players):
newName = input("\nEnter new Player name or 9 to quit: ")
wins = "0"
losses = "0"
ties = "0"
winpercent = "0"
if not newName:
print("\nNo name detected try again")
addplayer(players)
elif newName == '9':
print("\nReturning to Options menu")
else:
players[newName] = Player(newName,wins,losses,ties,winpercent)
saveData(players)
return players
Finally i am working on a sorted hi scores list. right now i can print my dictionary unsorted like this:
def printhiscores(players):
print("\n"," "*13,"HiScores")
print(" "*3,"Name"," "*20,"Wins")
if len(players) == 0:
print("\nNo current Players in memory.")
else:
for x in players.keys():
players[x].displayHighScores()
DisplayHighScores () being a part of the class object.
I have been reading on dictionary sorting using
OrderedDict(sorted(players.items(), key=itemgetter(1)))
but this returns edit:TypeError: '<' not supported between instances of 'Player' and 'Player'
Again I am looking to sort my dictionary of players by their win attribute and then print this new order to a high score screen. Any help would be greatly appreciated. I will post if i make any more progress on my own on this.
Your Player instances are not orderable however, as they don't implement comparison methods:
TypeError: '<' not supported between instances of 'Player' and 'Player'
If you wanted to sort them by the value returned, say, wins, then just access that information instead of just returning the value:
OrderedDict(sorted(players.items(), key=lambda kv: kv[1].getwins()))
Otherwise, give your Player class rich comparison methods; methods by which to determine when one instance should be sorted before or after another. You'll also need an equality test. It's easier to just implement support for < (lower then) and equality, then use the #functools.total_ordering decorator to provide the rest:
from functools import total_ordering
#total_ordering
class Player:
def __lt__(self, other):
if not isinstance(other, Player):
return NotImplemented
return self.__wins < other.__wins
def __eq__(self, other):
if not isinstance(other, Player):
return NotImplemented
return self.__wins == other.__wins
The above makes two Player instances equal when their wins are equal, and orders them by that attribute. You'll need to adjust this for your application as needed.

Resources