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)
Related
I'm trying to create a function that checks for balance brackets, according to the class I created.
But I keep getting False all the time.
I would really appreciate if you could show me where I was wrong and explain me the solution to my mistake.
class Stack:
def __init__(self):
self.__items = []
self.__top = 0
def is_Empty(self):
if self.__top <= 0:
return "Stack Empty!"
else:
return f"Your stack is not Empty!\nThe current stack is {self.my_stack()}"
def __str__(self):
"""Print current stack"""
return self.my_stack()
def push(self, item):
"""Push item in stack."""
self.__items.append(item)
self.__top += 1
def pop(self):
"""Remove top of the stack."""
if self.__top <= 0:
return self.is_Empty()
self.__top -= 1
return self.__items.pop()
def top(self):
"""Return top of the stack."""
if self.__top <= 0:
return self.is_Empty()
else:
return self.__items[-1]
def my_stack(self):
"""Show the current stack"""
if not self.__items:
return self.is_Empty()
else:
return f"The current stack is {self.__items}"
def check_balance(test):
"""
Return True if brackets are balanced, False otherwise.
"""
oppositeBracket = {']': '[', ')': '(', '}': '{'}
lefts = Stack()
for char in test:
if char in '[({':
lefts.push(char)
if char in '])}':
if lefts.is_Empty():
return False
else:
if lefts.top() != oppositeBracket[char]:
return False
lefts.pop()
if not lefts:
return True
return False
for example:
print(check_balance("(10+10)"))
And I get
False
You have 2 small bugs in your code:
isEmpty method returns always True since you return non empty string.
Your final check for empty stack (if not lefts) is always True as well since lefts is equal to your stack object and it even if it's empty, it won't be logical False.
The code should be:
class Stack:
def __init__(self):
self.__items = []
self.__top = 0
def is_Empty(self):
return self.__top <= 0
def __str__(self):
"""Print current stack"""
return self.my_stack()
def push(self, item):
"""Push item in stack."""
self.__items.append(item)
self.__top += 1
def pop(self):
"""Remove top of the stack."""
if self.__top <= 0:
return self.is_Empty()
self.__top -= 1
return self.__items.pop()
def top(self):
"""Return top of the stack."""
if self.__top <= 0:
return self.is_Empty()
else:
return self.__items[-1]
def my_stack(self):
"""Show the current stack"""
if not self.__items:
return self.is_Empty()
else:
return f"The current stack is {self.__items}"
def check_balance(test):
"""
Return True if brackets are balanced, False otherwise.
"""
oppositeBracket = {']': '[', ')': '(', '}': '{'}
lefts = Stack()
for char in test:
if char in '[({':
lefts.push(char)
elif char in '])}':
if lefts.is_Empty():
return False
else:
if lefts.top() != oppositeBracket[char]:
return False
lefts.pop()
return lefts.is_Empty()
You are treating is_Empty as returning a boolean, but it doesn't. It returns a string in either case. (and such is always "True" in a boolean sense)
UnitTest:
l = Stack()
l.push('1')
assert not l.is_Empty()
This assert should not fail, but does.
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()
So I am trying some things with linked lists using Node, tail and empty but I have no clue on how to make a summs_even or summs_odd function.
class Node:
def __init__(self, value, tail):
self.IsEmpty = False
self.Value = value
self.Tail = tail
def __str__(self):
return str(Node)
class Empty:
def __init__(self):
self.IsEmpty = True
Empty = Empty()
l = Node(1, Node(2, Node(3, Node(4, Empty))))
def summ(l):
if l.IsEmpty:
return 0
else:
return l.Value + summ(l.Tail)
print("Sum: " + str(summ(l)))
Something along the lines
def summ_even(l):
if l.IsEmpty:
return 0
elif l.Value%2==1: # check if value is odd
return summ_even(l.Tail)
else:
return return l.Value + summ_even(l.Tail)
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.
I've been going over some of the many coding interview questions. I was wondering how you would go about implementing a queue using two stacks in Python? Python is not my strongest language so I need all the help I can get.
Like the enqueue, dequeue, and front functions.
class Queue(object):
def __init__(self):
self.instack=[]
self.outstack=[]
def enqueue(self,element):
self.instack.append(element)
def dequeue(self):
if not self.outstack:
while self.instack:
self.outstack.append(self.instack.pop())
return self.outstack.pop()
q=Queue()
for i in range(10):
q.enqueue(i)
for i in xrange(10):
print q.dequeue(),
class MyQueue(object):
def __init__(self):
self.first = []
self.second = []
def peek(self):
if not self.second:
while self.first:
self.second.append(self.first.pop());
return self.second[len(self.second)-1];
def pop(self):
if not self.second:
while self.first:
self.second.append(self.first.pop());
return self.second.pop();
def put(self, value):
self.first.append(value);
queue = MyQueue()
t = int(raw_input())
for line in xrange(t):
values = map(int, raw_input().split())
if values[0] == 1:
queue.put(values[1])
elif values[0] == 2:
queue.pop()
else:
print queue.peek()
class Stack:
def __init__(self):
self.elements = []
def push(self, item):
self.elements.append(item)
def pop(self):
return self.elements.pop()
def size(self):
return len(self.elements)
def is_empty(self):
return self.size() == 0
class CreatingQueueWithTwoStacks:
def __init__(self):
self.stack_1 = Stack()
self.stack_2 = Stack()
def enqueue(self, item):
self.stack_1.push(item)
def dequeue(self):
if not self.stack_1.is_empty():
while self.stack_1.size() > 0:
self.stack_2.push(self.stack_1.pop())
res = self.stack_2.pop()
while self.stack_2.size() > 0:
self.stack_1.push(self.stack_2.pop())
return res
if __name__ == '__main__':
q = CreatingQueueWithTwoStacks()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
a = q.dequeue()
print(a)
b = q.dequeue()
print(b)
c = q.dequeue()
print(c)
d = q.dequeue()
print(d)
q.enqueue(5)
q.enqueue(6)
print(q.dequeue())
First, create a stack object. Then create a queue out of 2 stacks. Since a Stack = FIFO (first in first out), and Queue = LIFO (last in first out), add all the items to the "in stack" and then pop them into the output.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def is_empty(self):
return self.items == []
class Queue2Stacks(object):
def __init__(self):
# Two Stacks
self.in_stack = Stack()
self.out_stack = Stack()
def enqueue(self, item):
self.in_stack.push(item)
def dequeue(self):
if self.out_stack.is_empty:
while self.in_stack.size()>0:
self.out_stack.push(self.in_stack.pop())
return self.out_stack.items.pop()
#driver code
q = Queue2Stacks()
for i in range(5):
q.enqueue(i)
for i in range(5):
print(q.dequeue(i))
Gives you 0,1,2,3,4
Stack1, Stack2.
Enqueue:
Push el into stack1.
Dequeue:
While (!empty(Stack1))
el = Pop from stack1
Push el into stack2
returnEl = Pop from Stack2
While (!empty(Stack2))
el = Pop from stack2
Push el into stack1
return returnEl
That is a way of implementing the algorithm in pseudocode, it shouldn`t be difficult to implement it in python knowing the basic syntax.
I found this solution that works for implementing a queue using two stacks. I use set instead of queue. We can use the following implementation. for the time cost of m function calls on your queue. This optimization can be any mix of enqueue and dequeue calls.
#
#
class Stack():
def __init__(self):
self.stk = []
def pop(self):
"""raises IndexError if you pop when it's empty"""
return self.stk.pop()
def push(self, elt):
self.stk.append(elt)
def is_empty(self):
return len(self.stk) == 0
def peek(self):
if not self.stk.is_empty():
return self.stk[-1]
class Queue():
def __init__(self):
self.q = Stack() # the primary queue
self.b = Stack() # the reverse, opposite q (a joke: q vs b)
self.front = None
def is_empty(self):
return self.q.is_empty()
def peek(self):
if self.q.is_empty():
return None
else:
return self.front
def enqueue(self, elt):
self.front = elt
self.q.push(elt)
def dequeue(self):
"""raises IndexError if you dequeue from an empty queue"""
while not self.q.is_empty() > 0:
elt = self.q.pop()
self.b.push(elt)
val = self.b.pop()
elt = None
while not self.b.is_empty() > 0:
elt = self.b.pop()
self.q.push(elt)
self.front = elt
return val
# Now let's test
class TestQueueTwoStacks(unittest.TestCase):
def setUp(self):
self.q = Queue()
def test_queuedequue(self):
"""queue up 5 integers, check they are in there, dequeue them, check for emptiness, perform other blackbox and whitebox tests"""
self.assertTrue(self.q.is_empty())
self.assertTrue(self.q.q.is_empty())
self.assertTrue(self.q.b.is_empty())
l = range(5)
for i in l:
self.q.enqueue(i)
self.assertEqual(4, self.q.peek())
self.assertEqual(l, self.q.q.stk)
s = []
l.reverse()
for i in l:
elt = self.q.dequeue()
s.append(elt)
self.assertTrue(self.q.is_empty())
self.assertTrue(self.q.q.is_empty())
self.assertTrue(self.q.b.is_empty())
l.reverse()
self.assertEqual(s, l)
self.assertEqual([], self.q.b.stk)
self.assertEqual([], self.q.q.stk)
if __name__ == "__main__":
# unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestQueueTwoStacks)
unittest.TextTestRunner(verbosity=2).run(suite)