Exemplo n.º 1
0
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
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)
Exemplo n.º 3
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
Exemplo n.º 4
0
 def test_size(self):
     """
 Test for size method
 """
     stack = Stack()
     self.assertEqual(stack.size(), 0)
     stack.push(1)
     self.assertEqual(stack.size(), 1)
 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)
 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))
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
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_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))
Exemplo n.º 11
0
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 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
Exemplo n.º 13
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()
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
Exemplo n.º 15
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
Exemplo n.º 16
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())
Exemplo n.º 17
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)
Exemplo n.º 18
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
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
Exemplo n.º 20
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()
Exemplo n.º 21
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
Exemplo n.º 22
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
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
 def test_stack_not_empty_after_push(self):
     stack = Stack()
     stack.push(0)
     assert not stack.empty()
Exemplo n.º 25
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)
Exemplo n.º 26
0
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)