Esempio n. 1
0
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
Esempio n. 2
0
 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 test_new_stack_is_empty(self):
     """
     Create an empty Stack.
     Test that its size is 0.
     """
     stack = Stack()
     self.assertTrue(stack.empty())
     self.assertEqual(stack.size(), 0)
 def test_new_stack_from_generator(self):
     """
     Create a Stack from a generator.
     Test that its size equals to the number provided in the generator.
     """
     stack = Stack(range(10))
     self.assertFalse(stack.empty())
     self.assertEqual(stack.size(), 10)
     self.assertEqual(stack.top(), 9)
 def test_push(self):
     length = 100
     s = Stack()
     lst = []
     for i in range(length):
         s.push(i)
         lst.append(i)
     self.assertEqual(len(s), length)
     self.assertEqual(str(lst), str(s))
 def test_new_stack_from_list(self):
     """
     Create a Stack from a list.
     Check that the size of stack equals to the size of the list.
     Check that the top element of stack equals to the latest element of the list.
     """
     data_to_stack = (1, 3, 5, 7, 2, 4)
     stack = Stack(data_to_stack)
     self.assertFalse(stack.empty())
     self.assertEqual(stack.size(), len(data_to_stack))
     self.assertEqual(stack.top(), data_to_stack[-1])
Esempio n. 7
0
 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)
Esempio n. 8
0
 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)
 def test_call_pop_of_empty_stack_raised_error(self):
     """
     Create an empty Stack.
     Test that call of pop function raises Value error
     """
     stack = Stack()
     self.assertRaises(ValueError, stack.pop)
Esempio n. 10
0
 def test_push(self):
     """
 Test for push method
 """
     stack = Stack()
     self.assertEqual(stack.size(), 0)
     stack.push(1)
     stack.push(2)
     stack.push(3)
     self.assertEqual(stack.size(), 3)
Esempio n. 11
0
    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 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())
Esempio n. 13
0
class TowerOfHanoi:
    def __init__(self):
        self.pegA = Stack("A")
        self.pegB = Stack("B")
        self.pegC = Stack("C")

    def init_discs(self, n=3):
        for i in range(n, 0, -1):
            self.pegA.push(i)

    def transfer(self, frm, to, via, n):
        if n == 1:
            el = frm.pop()
            to.push(el)
            print("{} moved from {} to {}".format(el, frm.name, to.name))
        else:
            self.transfer(frm=frm, to=via, via=to, n=n - 1)
            self.transfer(frm, to, via, n=1)
            self.transfer(frm=via, to=to, via=frm, n=n - 1)

    def start(self):
        self.transfer(self.pegA, self.pegC, self.pegB, self.pegA.size())
Esempio n. 14
0
 def test_size(self):
     """
 Test for size method
 """
     stack = Stack()
     self.assertEqual(stack.size(), 0)
     stack.push(1)
     self.assertEqual(stack.size(), 1)
Esempio n. 15
0
 def test_stack_length_matches_number_of_pushes(self):
     stack = Stack()
     assert len(stack) == 0
     stack.push(0)
     assert len(stack) == 1
     stack.push(1)
     stack.push(2)
     assert len(stack) == 3
 def test_push_element(self):
     """
     Push an element in stack.
     Test that its size is 1.
     """
     stack = Stack()
     stack.push(None)
     self.assertFalse(stack.empty())
     self.assertEqual(stack.size(), 1)
Esempio n. 17
0
    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
 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))
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 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 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
from data_structures.stack.node import Node
from data_structures.stack.stack import Stack

stack1 = Stack()
stack2 = Stack()


def enqueue(self, val):
    """This method inserts value into the Queue using FIFO using stacks push pop methods."""
    node = Node(val, self.top)
    stack1.push(node)
    return self.top


def dequeue():
    """This method extracts a value from the queue using FIFO using stacks push pop methods. """
    if stack2.top is not None:
        return stack2.pop()
    while stack1.top is not None:
        node = stack1.pop()
        stack2.push(node)
        return stack1.pop()
Esempio n. 23
0
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()
Esempio n. 24
0
 def __init__(self):
     self.stack = Stack()
Esempio n. 25
0
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)
Esempio n. 26
0
 def test_initialization(self):
     stack = Stack()
     assert isinstance(stack, Stack)
Esempio n. 27
0
    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()
Esempio n. 28
0
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)
Esempio n. 29
0
 def setUp(self):
     self.stack = Stack()
Esempio n. 30
0
 def test_top_gets_last_pushed_value(self):
     stack = Stack()
     stack.push(0)
     assert stack.top() == 0
     stack.push(1)
     assert stack.top() == 1
     stack.push(2)
     assert stack.top() == 2