I am trying to create a Python object from the class below, but when I call the method popit(), I am getting a None. Any help as to what I miss or do wrong is appreciated.
class Stack:
def __init__(self, *item):
self.stack = []
def pushit(self, item):
if len(self.stack) == 9:
print("Stack is full: " + self.stack)
else:
print(self.stack.append(self.item))
def popit(self):
if self.stack == []:
print("Stack underflow: " + self.stack)
else:
print(self.stack.pop())
Your methods -- both of them -- don't return anything. What I would do to sort this is:
class Stack:
def __init__(self):
self.stack = []
def pushit(self, item):
if len(self.stack) == 9:
print("Stack is full: " + self.stack)
return None
else:
print(self.stack.push(self.item))
return self.item
def popit(self):
if self.stack == []:
print("Stack underflow: " + self.stack)
return None
else:
ret = self.stack.pop()
print(ret)
return ret
Related
I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.---> 50 result = checkBrackets(equation)
I did define the class as below but it gives me error message says, name 'checkBrackets' is not defined.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
statck.push(ch)
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flg, size)
equation = input ("Enter_qauation: ")
result = checkBrackets(equation)
print ("%s_%d"%(result[0],result[1]))
The function is defined, but it is defined in the class Stack so you need to call it as Stack.checkBrackets(equation). There were two more errors(spelling errors), so the final code looks like:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def isEmpty (self):
return len(self.stack) == 0
def peek (self):
if len(self.stack) != 0:
return self.stack[-1]
def pop(self):
if len(self.stack) != 0:
return self.stack.pop(-1)
###
def checkBrackets(statement):
stack = Stack()
size = 0
flag = "Wrong"
for ch in statement:
if ch in ('{','[','('):
size += 1
stack.push(ch) # spelling correction
elif ch in ('}',']',')'):
size += 1
if stack.isEmpty():
return (flag, size)
else:
left = stack.pop()
if (ch=="}" and left !="{") or (ch=="]" and left !="[") or (ch==")" and left !="(") :
return (flag, size)
if stack.isEmpty():
flag ="OK"
return (flag, size)
else:
return (flag, size) # spelling correction
equation = input ("Enter_equation: ")
result = Stack.checkBrackets(equation) # Changed Line
print ("%s_%d"%(result[0],result[1]))
Sample Output 1:
Enter_qauation:
(1+2)=3
OK_2
Sample Output 2:
Enter_qauation:
1+2=(3
Wrong_1
I tried to check and fix the code but I just can't find what is the problem anywhere with this code
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class BinaryTree:
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
if self.left_child == None:
self.left_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.left_child = self.left_child
self.left_child = t
def insert_right(self, new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.right_child = self.right_child
self.right_child = t
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self, obj):
self.key = obj
def get_root_val(self):
return self.key
def preorder(tree):
if tree:
print(tree.get_root_val())
preorder(tree.get_left_child())
preorder(tree.get_right_child())
def postorder(tree):
if tree != None:
postorder(tree.get_left_child())
postorder(tree.get_right_child())
print(tree.get_root_val())
def inorder(tree):
if tree != None:
inorder(tree.get_left_child())
print(tree.get_root_val())
inorder(tree.get_right_child())
def build_parse_tree(fp_exp):
fp_list = fp_exp.split()
p_stack = Stack()
e_tree = BinaryTree('')
p_stack.push(e_tree)
current_tree = e_tree
for i in fp_list:
if i == '(':
current_tree.insert_left('')
p_stack.push(current_tree)
current_tree = current_tree.get_left_child()
elif i not in ['+', '-', '*', '/', ')']:
current_tree.set_root_val(int(i))
parent = p_stack.pop()
current_tree = parent
elif i in ['+', '-', '*', '/']:
current_tree.set_root_val(i)
current_tree.insert_right('')
p_stack.push(current_tree)
current_tree = current_tree.get_right_child()
elif i == ')':
current_tree = p_stack.pop()
else:
raise ValueError
return e_tree
if __name__ == '__main__':
pt = build_parse_tree("( ( 10 + 5 ) * ( 3 - 2 ) )")
pt.postorder()
I run the code and it's return me with this
name 'postorder' is not defined
File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 63, in postorder
postorder(tree.get_left_child())
File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 102, in <module>
pt.postorder()
I tried to make it a recursive function but I don't know what am I doing wrong or what might I be missing.
I'm still checking the code but I just can't find missing things
Your traversal methods preorder, postorder and inorder have declarations that you would expect for standalone functions, but they are indented to be part of the class and so they look like methods.
The easiest fix is to move them out of the class block and replace the call in your main program with postorder(pt), and it will work.
If you prefer to have them as methods on your class, so that you can make the call like pt.postorder(), then rename the parameter tree to self (as that is the common practice), make the recursive calls in method-notation, and move the if condition before the recursive calls:
def postorder(self):
print(self.get_root_val())
if self.get_left_child():
self.get_left_child().postorder()
if self.get_right_child():
self.get_right_child().postorder()
For completeness sake, I provide also an alternative that leaves the if condition at the start, but then you must use another syntax on the recursive calls, as you cannot call a method on None:
def postorder(self):
if self:
print(self.get_root_val())
BinaryTree.postorder(self.get_left_child())
BinaryTree.postorder(self.get_right_child())
But this is not normal practice in Python.
Sorry for all of the code, but for this assignment I am working on, it is necessary due to different references.
This chapter we are working with Binary Trees and Binary Search Trees.
I tested the BinaryTree() and BinarySearchTree() classes with no issue.
My problem is this: we are adding records to a binary search tree as seen in the Student class and the main() function to test the class. According to the assignment:
The Student class has an id and name, getters and setters, a str() function so that you can print a student record, and the operations ==, !=, <=, <, >=, > defined. The comparison operators compare student id's which are intended to be unique. Since we can compare student records, we can now put them into a Binary Search Tree.
My question is, how do I add the records a binary tree if all of the initialized variables are completely different than ones in the BinaryTree() class and the BinarySearchTree() class?
Everytime I run the code, I get errors such as:
AttributeError: 'Student' object has no attribute 'insert'
or
isEmpty() = True
None
isEmpty() = False
None
101(Betty Smith)
101(Betty Smith)
Traceback (most recent call last):
File "/Users/phillipward/Desktop/Lab 10/StudentRecordsTest.py", line 50, in <module>
main()
File "/Users/phillipward/Desktop/Lab 10/StudentRecordsTest.py", line 22, in main
BST.insert(Student(42, "Amy Winchester"))
File "/Users/phillipward/Desktop/Lab 10/BinarySearchTree.py", line 13, in insert
self.getleftChild().insert(data)
File "/Users/phillipward/Desktop/Lab 10/BinarySearchTree.py", line 7, in insert
if(self.isEmpty()):
File "/Users/phillipward/Desktop/Lab 10/binaryTree.py", line 33, in isEmpty
if(self is None or self.data is None):
AttributeError: 'Student' object has no attribute 'data'
I'm stuck on how to tell the program that I the student class is a type of BinarySearchTree.
class BinaryTree():
def __init__(self, data = None, leftChild = None, rightChild = None):
self.data = data
self.leftChild = leftChild
self.rightChild = rightChild
def getData(self):
return self.data
def setData(self, x):
self.data = x
return self.data
def getleftChild(self):
return self.leftChild
def setleftChild(self, x):
self.leftChild = x
return self.leftChild
def getrightChild(self):
return self.rightChild
def setrightChild(self, x):
self.rightChild = x
return self.rightChild
def isEmpty(self):
if(self is None or self.data is None):
return True
else:
return False
def __str__ (self):
return "{0}".format(self.data)
def inOrderTraversal(self):
if (self is None):
return "Empty"
else:
result = ""
if(self.getleftChild() is not None): # When we put payload in, we need equality
result += BinaryTree.inOrderTraversal(self.getleftChild()) + " "
result += str(self.getData())
if (self.getrightChild() is not None):
result += " " + BinaryTree.inOrderTraversal(self.getrightChild()) + " "
return result
def preOrderTraversal(self):
if (self.isEmpty()):
return "Empty"
else:
result = ""
result += str(self.getData())
if (self.getleftChild() is not None):
result += " " + BinaryTree.preOrderTraversal(self.getleftChild()) + " "
if (self.getrightChild() is not None):
result += BinaryTree.preOrderTraversal(self.getrightChild())
return result
def postOrderTraversal(self):
if (self.isEmpty()):
return "Empty"
else:
result = ""
if (self.getleftChild() is not None):
result += BinaryTree.postOrderTraversal(self.getleftChild()) + " "
if (self.getrightChild() is not None):
result += BinaryTree.postOrderTraversal(self.getrightChild()) + " "
result += str(self.getData())
return result
def insert(self, data):
if (self.isEmpty()):
self.setData(data)
elif (data < self.getData()):
if (self.getleftChild() is None):
self.setleftChild(BinarySearchTree(data))
else:
self.getleftChild().insert(data)
else: # data >= self.getData()
if (self.getrightChild() is None):
self.setrightChild(BinarySearchTree(data))
else:
self.getrightChild().insert(data)
def retrieve(self, data):
if self.isEmpty():
return None
elif data == self.getData():
return self.getData()
elif data <= self.getData():
if self.getleftChild() is None:
return None
else:
return self.getleftChild().retrieve(data)
else:
if self.getrightChild() is None:
return None
else:
return self.getrightChild().retrieve(data)
from binaryTree import BinaryTree
class BinarySearchTree(BinaryTree):
def insert(self, data):
if(self.isEmpty()):
self.setData(data)
elif(data < self.getData()):
if(self.getleftChild() is None):
self.setleftChild(data)
else:
self.getleftChild().insert(data)
else: #data >= self.getData()
if(self.getrightChild() is None):
self.setrightChild(data)
else:
self.getrightChild().insert(data)
def retrieve(self, data):
if self.isEmpty():
return None
elif data == self.getData():
return self.getData()
elif data <= self.getData():
if self.getleftChild() is None:
return None
else:
return self.getleftChild().retrieve(data)
else:
if self.getrightChild() is None:
return None
else:
return self.getrightChild().retrieve(data)
def minValue(self):
current = self
while current.leftChild is not None:
current = current.leftChild
return current.data
def maxValue(self):
current = self
while current.rightChild is not None:
current = current.rightChild
return current.data
def isBST(self):
current = self
if current == None:
return True
if current.leftChild.data <= current.data and
current.rightChild.data >= current.data:
return True
else:
return False
class Student():
def __init__(self, id = None, name = ""):
self.__id = id
self.__name = name
def getId(self):
return self.__id
def setId(self, id):
self.__id = id
def getName(self):
return self.__name
def setName(self, name):
self.__id = name
def __str__(self):
if (self is None):
return ""
else:
return str(self.__id) + "(" + self.__name + ")"
def __cmp__(self, other):
if (self is None or other is None):
return 0
else:
return self.__id - other.__id
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
from BinarySearchTree import BinarySearchTree
from Student import Student
def main():
BST = BinarySearchTree()
print("isEmpty() = " + str(BST.isEmpty()))
print(BST)
BST.setData(Student(101, "Betty Smith"))
print("isEmpty() = " + str(BST.isEmpty()))
print(BinarySearchTree())
BST.insert(Student(50, "John Adams"))
print(BST)
BST.insert(Student(250, "Mike Jones"))
print(BST)
BST.insert(Student(42, "Amy Winchester"))
print(BST)
BST.insert(Student(31, "Jill Ranger"))
print(BST)
BST.insert(Student(315, "Bob Crachet"))
print(BST)
BST.insert(Student(200, "Karen Wilkins"))
print(BST)
print("\n")
print()
print("Inorder traversal: " + str(BST))
print()
print("Preorder traversal: \n" + BST.preOrderTraversal())
print()
print("Postorder traversal: " + BST.postOrderTraversal())
print()
print("minValue: " + str(BST.minValue()))
print("maxValue: " + str(BST.maxValue()))
print()
print("isBST = " + str(BST.isBST()))
for id in [101, 200, 31, 50, 315, 250, 42]:
print(BST.retrieve(Student(id)))
main()
I want to try to convert a decimal number to a binary number using stacks in Python but I got this error.
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def divideBy2(decNumber):
remstack = Stack()
while decNumber > 0:
rem = decNumber % 2
remstack.push(rem)
decNumber = decNumber // 2
binString = ""
while not remstack.is_empty():
binString = binString + str(remstack.pop())
return binString
print(divideBy2(42))
Your pop method is missing a return.
So I created a simple class method to reverse a string and yet it returns to me the original? The Method that I created works outside of the class but for some reason it does not when I try to implement it.
See my code below:
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
def pop(self):
return self.__items.pop()
def peek(self):
return self.__items[len(self.__items)-1]
def is_empty(self):
return len(self.__items) == 0
def size(self):
return len(self.__items)
def reverse(self):
if len(self.__items) <= 1:
return self.__items
return self.__items.reverse(self.__items[1:]) + self.__items[0]
s=Stack()
rev=input("Enter string to reverse; ")
s.push(rev)
print(s.reverse())
You need to reverse each string in self.__items not self.__items itself:
def reverse(self):
if not self.__items: # if items is empty return empty string
return ""
return " ".join(s[::-1] for s in self.__items)
self.__items[::-1] will reverse the list items not the string/strings inside.
If you wanted to do it without slicing:
def reverse(self):
if not self.__items:
return ""
out = ""
for item in self.__items:
temp = ""
for i in range(len(item)-1, -1, -1):
temp += item[i]
out += temp
return out
Or recursively:
def reverse(self):
if not self.__items:
return ""
def recur(s):
if not s:
return ""
return s[-1] + recur(s[:-1])
return " ".join(recur(w) for w in self.__items)