def build_parse_tree(expr): tokens = expr.split() stack = Stack() tree = BinaryTree('') stack.push(tree) current_tree = tree for token in tokens: if token == '(': current_tree.insert_left('') stack.push(current_tree) current_tree = current_tree.get_left_child() # If token is an operand (e.g. a number) elif token not in ['+', '-', '*', '/', ')']: try: current_tree.set_root(int(token)) parent = stack.pop() current_tree = parent except ValueError: raise ValueError(f'Token {token} is not a valid integer') elif token in ['+', '-', '*', '/']: current_tree.set_root(token) current_tree.insert_right('') stack.push(current_tree) current_tree = current_tree.get_right_child() elif token == ')': current_tree = stack.pop() return tree
class ReversePolishNotationCalculator: """ Calculator of expression in Reverse Polish Notation """ def __init__(self): self.stack = Stack() def calculate(self, rpn_expression: ReversePolishNotation) -> float: """ Main method of the ReversePolishNotationCalculator class. Calculating result of expression in Reverse Polish Notation. :param rpn_expression: expression in Reverse Polish Notation Format :return: result of the expression """ for element in rpn_expression: if isinstance(element, Op): res = self._calculate_value(element) self.stack.push(res) else: self.stack.push(element) return self.stack.top().digit def _calculate_value(self, operator: Op) -> Digit: first = self.stack.top() self.stack.pop() second = self.stack.top() self.stack.pop() return operator(first, second)
class ReversePolishNotationCalculator: """ Calculator of expression in Reverse Polish Notation """ def __init__(self): self.stack = Stack() def calculate(self, rpn_expression: ReversePolishNotation) -> float: """ Main method of the ReversePolishNotationCalculator class. Calculating result of expression in Reverse Polish Notation. :param rpn_expression: expression in Reverse Polish Notation Format :return: result of the expression """ for el in rpn_expression: if isinstance(el, Digit): self.stack.push(el) if isinstance(el, Op): hitotsu = self.stack.top() self.stack.pop() futatsu = self.stack.top() self.stack.pop() self.stack.push(el(hitotsu, futatsu)) res = self.stack.top() return res
def test_is_empty(self): """ Test for is_empty method """ stack = Stack() self.assertEqual(stack.is_empty(), True) stack.push(1) self.assertEqual(stack.is_empty(), False) stack.pop() self.assertEqual(stack.is_empty(), True)
def test_pop(self): """ Test for pop method """ stack = Stack() self.assertEqual(stack.pop(), None) stack.push(1) stack.push(2) stack.push(3) self.assertEqual(stack.pop(), 3) self.assertEqual(stack.size(), 2)
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def test_define_a_stack(self): self.assertIsInstance(self.stack, Stack) def test_if_stack_is_empty(self): self.assertTrue(self.stack.is_empty()) def test_if_stack_is_not_empty(self): self.stack.push(1) self.assertFalse(self.stack.is_empty()) def test_add_element_to_stack(self): self.stack.push(1) self.assertEquals(self.stack.stack, [1]) def test_add_element_to_an_fulfilled_stack(self): self.stack.push(1) with self.assertRaises(FullStackError): self.stack.push(2) def test_pop_an_element_to_stack(self): self.stack.push(1) element = self.stack.pop() self.assertEquals(element, 1) def test_pop_an_element_from_empty_stack(self): with self.assertRaises(EmptyStackError): self.stack.pop() def test_peek_an_element_from_stack(self): self.stack.max_size = 2 # Patch object's capacity self.stack.push(1) self.stack.push(2) element = self.stack.peek() self.assertEquals(element, 2) def test_peek_an_element_from_empty_stack(self): with self.assertRaises(EmptyStackError): self.stack.peek() def test_get_size_if_stack(self): self.stack.push(1) self.assertEquals(self.stack.size(), 1)
def test_pop_returns_and_removes_last_pushed_value(self): stack = Stack() stack.push(0) stack.push(1) stack.push(2) assert len(stack) == 3 assert stack.pop() == 2 assert len(stack) == 2 assert stack.pop() == 1 assert len(stack) == 1 assert stack.pop() == 0 assert len(stack) == 0 with raises(Stack.EmptyStackException): stack.pop()
def test_push_sequence_of_elements(self): """ Push a sequence of elements in stack. Test that its size equals to the length of the given sequence. Pop all elements from stack and check reversed order. """ stack = Stack() elements = (1, 2, "string", None, 0, Stack()) map(stack.push, elements) self.assertEqual(stack.size(), len(elements)) for index, element in enumerate(reversed(elements)): top = stack.top() self.assertEqual(top, element) stack.pop() number_pop_elements = index + 1 expected_current_stack_size = len(elements) - number_pop_elements self.assertEqual(stack.size(), expected_current_stack_size) self.assertTrue(stack.empty())
def test_pop(self): length = 100 s = Stack() lst = [] for i in range(length): s.push(i) lst.append(i) while s.has_more(): s_item = s.pop() lst_item = lst.pop() self.assertEqual(s_item, lst_item) self.assertEqual(len(s), len(lst))
class ReversePolishNotationCalculator: """ Calculator of expression in Reverse Polish Notation """ def __init__(self): self.stack = Stack() def calculate(self, rpn_expression: ReversePolishNotation) -> float: for element in rpn_expression: if isinstance(element, Op): res = self.calculate_value(element) self.stack.push(res) else: self.stack.push(element) return self.stack.top() def _calculate_value(self, operator: Op) -> Digit: first = self.stack.top() self.stack.pop() second = self.stack.top() self.stack.pop() return operator.function(first, second)
class QueueTests(unittest.TestCase): def setUp(self): self.stack = Stack() def test_len_returns_0_for_empty_stack(self): self.assertEqual(len(self.stack), 0) def test_len_returns_correct_length_after_push(self): self.assertEqual(len(self.stack), 0) self.stack.push(2) self.assertEqual(len(self.stack), 1) self.stack.push(4) self.assertEqual(len(self.stack), 2) self.stack.push(6) self.stack.push(8) self.stack.push(10) self.stack.push(12) self.stack.push(14) self.stack.push(16) self.stack.push(18) self.assertEqual(len(self.stack), 9) def test_empty_pop(self): self.assertIsNone(self.stack.pop()) self.assertEqual(len(self.stack), 0) def test_pop_respects_order(self): self.stack.push(100) self.stack.push(101) self.stack.push(105) self.assertEqual(self.stack.pop(), 105) self.assertEqual(len(self.stack), 2) self.assertEqual(self.stack.pop(), 101) self.assertEqual(len(self.stack), 1) self.assertEqual(self.stack.pop(), 100) self.assertEqual(len(self.stack), 0) self.assertIsNone(self.stack.pop()) self.assertEqual(len(self.stack), 0)
def base_converter(num, base): digits = '0123456789ABCDEF' stack = Stack() while num > 0: remainder = num % base stack.push(remainder) num = num // base binary_str = "" while not stack.is_empty(): binary_str += digits[stack.pop()] return binary_str
def multi_bracket_validation(s): """Function that determines if brackets are balanced. args: a string output: a boolean """ opening = ['(', '[', '{'] closing = [')', ']', '}'] stack = Stack() for i in range(len(s)): if s[i] in opening: stack.push(s[i]) if s[i] in closing: if not len(stack): return False elif opening[closing.index(s[i])] != stack.top.value: return False else: stack.pop() if len(stack): return False else: return True
class ReversePolishNotationCalculator: """ Calculator of expression in Reverse Polish Notation """ def __init__(self): self.stack = Stack() self.ops = { "+": (lambda a, b: a + b), "-": (lambda a, b: a - b), "*": (lambda a, b: a * b), "/": (lambda a, b: a / b) } def calculate(self, expr) -> int: """ Main method of the ReversePolishNotationCalculator class. Calculating result of expression in Reverse Polish Notation. :param rpn_expression: expression in Reverse Polish Notation Format :return: result of the expression """ a = ReversePolishNotationConverter(expr) result = a.convert().split() for res in result: if res in self.ops: operand2 = self.stack.top() self.stack.pop() operand1 = self.stack.top() self.stack.pop() rst = self.ops[res](operand1, operand2) self.stack.push(rst) else: self.stack.push(float(res)) return self.stack.top()
def size(self): if self.root is None: return 0 stack = Stack() stack.push(self.root) size = 1 while stack: node = stack.pop() if node.left: size += 1 stack.push(node.left) if node.right: size += 1 stack.push(node.right) return size
def is_balanced(expr): stack = Stack() for elem in expr: if elem in '({[<': stack.push(elem) else: if stack.is_empty(): return False else: top = stack.pop() if top != symbol_map[elem]: return False if stack.is_empty(): return True else: return False
def is_balanced(string): stack = Stack("Brackets") for ch in string: if ch in ["(", "{", "["]: stack.push(ch) else: if ch == ")" and not stack.empty() and stack.peek() == "(": stack.pop() if ch == "}" and not stack.empty() and stack.peek() == "{": stack.pop() if ch == "]" and not stack.empty() and stack.peek() == "[": stack.pop() return False if stack else True
def _reverse_level_order_print(self, start): if start is None: return queue = Queue() stack = Stack() queue.enqueue(start) traversal = "" while len(queue) > 0: node = queue.dequeue() stack.push(node) if node.right: queue.enqueue(node.right) if node.left: queue.enqueue(node.left) while len(stack) > 0: node = stack.pop() traversal += str(node.value) + "-" return traversal
import time from data_structures.stack.stack import Stack, StackDeque stack1 = Stack() stack2 = StackDeque() start = time.time() for i in range(10000): stack1.push("ITEM") for i in range(10000): stack1.pop() stop = time.time() print(stop - start) start = time.time() for i in range(10000): stack2.push("ITEM") for i in range(10000): stack2.pop() stop = time.time() print(stop - start)