class TextStack(unittest.TestCase): def setUp(self): self.stack = Stack() self.stack.push(2) self.stack.push(5) self.stack.push(3) self.stack.push(1) self.stack.push(8) self.stackTwo = Stack() self.stackTwo.push(1) self.stackTwo.push(2) def test_push(self): self.stack.push(9) self.assertEquals(self.stack.__str__(), [2, 5, 3, 1, 8, 9]) with self.assertRaises(IndexError): self.stack.push(4) self.stack.push(2) def test_pop(self): self.stackTwo.pop() self.assertEquals(self.stackTwo.__str__(), [1, None, None, None, None, None]) with self.assertRaises(IndexError): self.stackTwo.pop() self.stackTwo.pop() self.stackTwo.pop()
class QueueWithTwoStacks(object): def __init__(self): self.s1 = Stack() self.s2 = Stack() def __str__(self): l1 = self.s2.__str__()[1:len(self.s2.__str__()) - 1].split(", ") l1.reverse() l3 = list(map(int, l1)) l2 = list( map(int, self.s1.__str__()[1:len(self.s1.__str__()) - 1].split(", "))) if l2[0] is '': l2 = [] # print(l1[1:len(l1)-1]) return f'{list(l3+l2)}' def enqueue(self, item): self.s1.push(item) def dequeue(self): if self.s1.isEmpty() and self.s2.isEmpty(): raise Exception("Empty Queue") if self.s2.isEmpty(): while not self.s1.isEmpty(): self.s2.push(self.s1.pop()) return self.s2.pop() def peek(self): if self.s1.isEmpty() and self.s2.isEmpty(): raise Exception("Empty Queue") if self.s2.isEmpty(): while not self.s1.isEmpty(): self.s2.push(self.s1.pop()) return self.s2.peek()
def test_print(self): stack = Stack() assert stack.__str__() == '' # assert print(stack) == '' stack.push(3) stack.push(1) stack.push(2) assert stack.__str__() == '2 -> 1 -> 3'
from stack import Stack def sort(stack): tmp_stack = Stack() while stack.is_empty() is False: top = stack.pop() while tmp_stack.is_empty() is False and top < tmp_stack.peek(): stack.push(tmp_stack.pop()) tmp_stack.push(top) while tmp_stack.is_empty() is False: stack.push(tmp_stack.pop()) return stack stack = Stack() stack.push(3).push(1).push(5).push(8) sort(stack) print(stack.__str__())
def main(): print('\n\nCreating empty ListStack named "a" of size 4') a = ListStack(4) print('Creating empty ListQueue named "b" of size 4') b = ListQueue(4) print('Creating empty Stack named "c" of size 4') c = Stack(4) print('Creating empty Queue named "d" of size 4') d = Queue(4) print("") print("PEEKING ON AN (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE") print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', b.peek(), 'currently contains', b.__str__()) print('peek on c', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print( " ----------- INSERTING VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for val in range(6): print('inserting', val, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)\n') print("") a.insert(val) b.insert(val) c.push(val) d.enqueue(val) print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', b.peek(), 'currently contains', b.__str__()) print('peek on c', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print( " ----------- REMOVING VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for i in range(4): print('Removing', i, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)') print('Before removing', a.peek(), 'from a', a.__str__()) a.remove() print('peek on a', a.peek(), 'after removing', a.__str__()) print("") print('Before removing', b.peek(), 'from b', b.__str__()) b.remove() print('peek on a', a.peek(), 'after removing', b.__str__()) print("") print('Before removing', c.peek(), 'from c', c.__str__()) c.pop() print('peek on c', c.peek(), 'after removing', c.__str__()) print("") print('Before removing', c.peek(), 'from d', d.__str__()) d.dequeue() print('peek on d', c.peek(), 'after removing', d.__str__()) print("") l = [10, 2, 23, 35, 76] print( " ----------- INSERTING USER DEFINED VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for val in l: print('inserting', val, 'into both a and b and c which is user defined') a.insert(val) b.insert(val) c.push(val) d.enqueue(val) print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', a.peek(), 'currently contains', b.__str__()) print('peek on b', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print("") print( " ----------- REMOVING USER DEFINED VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for i in l: print('Removing', i, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)') print('Before removing', a.peek(), 'from a', a.__str__()) a.remove() print('peek on a', a.peek(), 'after removing', a.__str__()) print("") print('Before removing', b.peek(), 'from b', b.__str__()) b.remove() print('peek on a', a.peek(), 'after removing', b.__str__()) print("") print('Before removing', c.peek(), 'from c', c.__str__()) c.pop() print('peek on c', c.peek(), 'after removing', c.__str__()) print("") print('Before removing', c.peek(), 'from d', d.__str__()) d.dequeue() print('peek on d', c.peek(), 'after removing', d.__str__()) print("")
def in2post(expr): """ Reformats an infix expression to a postfix expression. Process: Takes an infix expression as an input and returns an equivalent postfix expression as a string. If the expression is not valid, raise a SyntaxError. If the parameter expr is not a string, raise a ValueError. Args: expr(Str): An infix, str-type expression Returns: A postfix, str-type expression """ temp = expr stack = Stack() postfix = Stack() priority = {'^': 1, '*': 2, '/': 2, '+': 3, '-': 3} if isinstance(temp, str) is False: raise ValueError("Expression must be in string format.") count = 0 for char in temp: if char == '(': count += 1 if char == ')': count -= 1 if count != 0: raise SyntaxError("Not a valid expression") for char in temp: if char in ('\n', ' '): pass elif char == ')': while stack.peek() != '(': postfix.push(stack.pop()) stack.pop() elif char == '(': stack.push(char) elif char in priority: if stack.size() == 0: stack.push(char) elif priority.get(stack.peek()) == priority.get(char): postfix.push(stack.pop()) stack.push(char) elif stack.peek() != '(' and priority.get( stack.peek()) < priority.get(char): while stack.size() > 0: if stack.peek() != '(': postfix.push(stack.pop()) else: break stack.push(char) else: stack.push(char) else: postfix.push(char) if stack.size() != 0: while stack.size() != 0: postfix.push(stack.pop()) return postfix.__str__()
class StringProcessor: def __init__(self): self.stack = Stack() self.items = [] def reverse(self, string): res = '' for i in string: res = i + res return res def process_sequence(self, string): self.items = [] for i in string: if i != '*': self.items.append(i) elif (i != '') and (len(self.items) >= 1): self.items.pop(-1) res = '' for i in self.items: res = res + i return res def is_balanced(self, string): # self.items = string # # if (self.items[0] != '{') or (self.items[-1] != '}'): # return False # # d = 0 # for i in range(len(self.items)): # if self.items[i] == '{': # d += 1 # elif self.items[i] == '}': # d -= 1 # # if d == 0: # return True # else: # return False for i in string: if i == '{': self.stack.push(i) elif i == '}': if not self.stack.is_empty(): self.stack.pop() else: return False if self.stack.is_empty(): return True self.stack.clear() return False def binary_string(self, string): tg = string if self.stack.top is not None: self.stack.clear() while tg // 2 != 0: self.stack.push(str(tg % 2)) tg = tg // 2 self.stack.push(str(tg % 2)) return self.reverse(self.stack.__str__())
def test_make_a_stack_and_push_to_it(self): ms = Stack() ms.push('cat') ms.push(1337) ms.push(True) self.assertEqual(ms.__str__(), '(True) (1337) (cat) ')
def evalExpr(expr): def isMoreImportant(operator, stack_top_operator): if stack_top_operator == None: return False if operator in P_m_d: return True else: if stack_top_operator in P_m_d: return False else: return True def perfomOperator(op1, op, op2): if op == "+": return int(op1) + int(op2) elif op == "-": return int(op1) - int(op2) elif op == "*": return int(op1) * int(op2) else: return int(op1) / int(op2) operator = Stack() operand = Stack() num = list('0123456789') P_m_d = list('*/') P_a_s = list('-+') for char in expr: print(' -> ', operand.__str__()) print(' => ', operator.__str__()) if char in num: operand.push(char) elif char == '(': operator.push(char) elif char in P_m_d or char in P_a_s: while isMoreImportant(char, operator.peek()): if operator.peek() not in P_m_d and \ operator.peek() not in P_a_s: operator.push(char) else: if (operand.size() < 2): break op = operator.pop() op1 = operand.pop() op2 = operand.pop() operand.push(perfomOperator(op1, op, op2)) elif char == ')': while (operator.peek() != '('): op = operator.pop() op1 = operand.pop() op2 = operand.pop() operand.push(perfomOperator(op1, op, op2)) else: pass while not operator.isEmpty(): op = operator.pop() op1 = operand.pop() op2 = operand.pop() operand.push(perfomOperator(op1, op, op2)) return operand.peek()
def test(): """ :return: """ print('\n\n\nCreating empty Stack named "a" of size 3') a = Stack(4) for val in range(7): print('Inserting ', val, 'into a') a.push(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.pop() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty ListStack named "a" of size 3') a = ListStack(4) for val in range(7): print('Inserting ', val, ' into a') a.insert(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.remove() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty ListQueue named "a" of size 3') a = ListQueue(4) for val in range(7): print('Inserting ', val, ' into a') a.insert(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.remove() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty Ring Buffer Queue named "a" of size 3') a = Queue(4) for val in range(7): print('inserting', val, 'into a') a.enqueue(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('removing from a') a.dequeue() print(" " + a.__str__())
from stack import Stack if __name__ == '__main__': stickStack = Stack() print(stickStack.isEmpty()) stickStack.push(2) stickStack.push("Hello") print(stickStack.__str__()) print(stickStack.size()) print(stickStack.peek().data) print(stickStack.pop().data) print(stickStack.isEmpty()) stickStack.pop() print(stickStack.isEmpty()) print(stickStack.peek()) print(stickStack.pop())
from stack import Stack s = Stack() assert (s.is_empty()) assert (hasattr(s, "items")) assert (hasattr(s, "push")) assert (hasattr(s, "pop")) assert (hasattr(s, "is_empty")) s.push(5) assert (not s.is_empty()) assert (s.__str__() == "5") s.push(7) assert (not s.is_empty()) assert (s.__str__() == "5 7") s.push(-1) assert (not s.is_empty()) assert (s.__str__() == "5 7 -1") x = s.pop() assert (not s.is_empty()) assert (s.__str__() == "5 7") assert (x == -1) x = s.pop() assert (not s.is_empty()) assert (s.__str__() == "5") assert (x == 7)
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def test_str(self): self.assertEqual(self.stack.__str__(), '') self.stack.push(1) self.assertEqual(self.stack.__str__(), '1 ') self.stack.push(3) self.assertEqual(self.stack.__str__(), '3 1 ') def test_push(self): with self.assertRaisesRegex(Exception, "No value has been found"): self.stack.find(1) self.stack.push(1) self.assertEqual(self.stack.find(1), True) self.stack.push(2) self.assertEqual(self.stack.find(2), True) self.assertEqual(self.stack.count(), 2) def test_pop(self): with self.assertRaisesRegex(Exception, "Your list is empty."): self.stack.pop() self.stack.push(1) self.assertEqual(self.stack.find(1), True) self.stack.pop() with self.assertRaisesRegex(Exception, "No value has been found."): self.stack.find(1) def test_find(self): with self.assertRaisesRegex(Exception, "No value has been found."): self.stack.find(1) self.stack.push(1) self.stack.push(2) self.assertEqual(self.stack.find(1), True) self.assertEqual(self.stack.find(2), True) with self.assertRaisesRegex(Exception, "No value has been found."): self.stack.find(3) def test_count(self): self.assertEqual(self.stack.count(), 0) self.stack.push(1) self.assertEqual(self.stack.count(), 1) self.stack.push(1) self.assertEqual(self.stack.count(), 2) self.stack.pop() self.assertEqual(self.stack.count(), 1) def test_is_empty(self): self.assertEqual(self.stack.is_empty(), True) self.stack.push(1) self.assertEqual(self.stack.is_empty(), False) def test_getmin(self): with self.assertRaisesRegex(Exception, "Your Stack is empty."): self.stack.getmin() self.stack.push(2) self.assertEqual(self.stack.getmin(), 2) self.stack.push(1) self.assertEqual(self.stack.getmin(), 1) self.stack.push(0) self.assertEqual(self.stack.getmin(), 0)
from stack import Stack stack = Stack() stack.push("a") stack.push("b") stack.push("c") temp = stack.__str__() print(temp) for letter in range(97, 123): print(chr(letter))
class Calculator: CONSTANTS = {"e", "pi"} FUNCTIONS = {"sqrt": math.sqrt, "log": math.log, "exp": math.exp} OPERATIONS = {"+": 1, "-": 1, "*": 2, "/": 2, "%": 2, "**": 3} def __init__(self, expr, variables={}): self._tokens = Stack.from_list(tokenize(expr)) self._operators = Stack() self._arguments = Stack() self._variables = variables def evaluate(self): """Return the result of the function or raise a SyntaxError.""" while not self._tokens.is_empty(): next_operator = self._tokens.top() self._tokens.pop() if next_operator in self.CONSTANTS: self._arguments.push(self._get_constant(next_operator)) continue if isinstance(next_operator, int): self._arguments.push(next_operator) continue if (self._operators.is_empty() or next_operator == "("): self._operators.push(next_operator) continue top_operator = self._operators.top() if top_operator == "(" and next_operator == ")": self._operators.pop() elif (next_operator == ")" or self._eval_before(top_operator, next_operator)): self._pop_and_evaluate() self._tokens.push(next_operator) else: self._operators.push(next_operator) while not self._operators.is_empty(): self._pop_and_evaluate() result = self._arguments.top() self._arguments.pop() if not self._operators.is_empty() or not self._arguments.is_empty(): raise SyntaxError("The function could not be computed.") return result def _eval_before(self, stack_op, next_op): if stack_op == "(": return False stack_prec = self._get_precedence(stack_op) next_prec = self._get_precedence(next_op) if stack_prec > next_prec: return True elif stack_prec == next_prec: if stack_op == next_op: return stack_op in {"+", "-", "*", "/", "%"} return True return False def _get_precedence(self, operator): """Return the precedence of the given operator as int or raise an AssertionError.""" assert operator in self.FUNCTIONS or operator in self.OPERATIONS, ( f"Invalid operator {operator}.") if operator in self.FUNCTIONS: return 4 else: return self.OPERATIONS[operator] def _pop_and_evaluate(self): rhs = self._arguments.top() self._arguments.pop() op = self._operators.top() self._operators.pop() if op in self.FUNCTIONS: self._arguments.push(self._compute_function(rhs, op)) return lhs = self._arguments.top() self._arguments.pop() if op in self.OPERATIONS: self._arguments.push(self._compute_operation(lhs, rhs, op)) raise ValueError("Invalid operator {op}") def _get_constant(self, const): const = const.lower() assert const in self.CONSTANTS, f"Invalid constant {const}." if const == "e": return math.e elif const == "pi": return math.pi def _compute_operation(self, lhs, rhs, op): assert op in self.OPERATIONS, f"Invalid op {op}." if op == "+": return lhs + rhs elif op == "-": return lhs - rhs elif op == "*": return lhs * rhs elif op == "/": return lhs / rhs elif op == "%": return lhs % rhs elif op == "**": return lhs**rhs def _compute_function(self, arg, func): """Return the result of the given func with its argument, else raise an AssertError.""" assert func in self.FUNCTIONS, f"Invalid funktion {func}." if func in self.FUNCTIONS: if func == "sqrt": return math.sqrt(arg) elif func == "log": return math.log(arg) elif func == "exp": return math.exp(arg) def __str__(self): """Return the current state as a string for pretty printing.""" return (self._tokens.__str__() + self._arguments.__str__() + self._operators.__str__())