Exemplo n.º 1
0
def test_push():
    stack, arr = Stack(), []
    assert(stack.is_empty())
    for expected in range(ITERS):
        stack.push(expected)
        arr = [expected] + arr
        actual = stack.peek()
        assert(len(stack) == len(arr))
        assert(expected == actual)
        assert(not stack.is_empty())
def check_balanced_symbols(symbols_string):
    """Checks if opening and closing symbols in a string are balanced"""

    open_symbols = Stack()

    for symbol in symbols_string:
        if symbol in "({[":
            open_symbols.push(symbol)
        elif symbol in ")}]":
            if open_symbols.is_empty():
                return False
            open_symbol = open_symbols.pop()
            if not is_matching_symbols(open_symbol, symbol):
                return False

    return open_symbols.is_empty()
Exemplo n.º 3
0
def test_stack():
	stack = Stack()
	stack.push(3)
	stack.push(2)
	assert stack.peek() == 2
	assert stack.pop() == 2
	assert stack.pop() == 3
	assert stack.is_empty()
Exemplo n.º 4
0
def test_pop():
    stack, arr = Stack(), []
    assert(stack.is_empty())
    with pytest.raises(AssertionError):
        stack.pop()
    for _ in range(ITERS):
        expected = random.randrange(MAX_VAL)
        stack.push(expected)
        actual = stack.peek()
        arr = [expected] + arr
        assert(len(stack) == len(arr))
        assert(actual == expected)
    for _ in range(ITERS):
        expected, actual = arr[0], stack.pop()
        arr = arr[1:]
        assert(len(stack) == len(arr))
        assert(actual == expected)
    assert(stack.is_empty())
    with pytest.raises(AssertionError):
        stack.pop()
def parens_checker(parens_string):
    """Checks if parentheses in given string is balanced"""

    open_parens = Stack()

    for paren in parens_string:
        if paren == "(":
            open_parens.push(paren)
        else:
            if open_parens.is_empty():
                return False
            open_parens.pop()
    
    # if open_parens:
    #     return False
    # else:
    #     return True

    # The above can be simplified to a boolean check of is the stack empty

    return open_parens.is_empty()
def rev_string(my_string):
    """Uses stack to reverse characters in string"""
    chars = Stack()

    for char in my_string:
        chars.push(char)

    reversed_string = ''

    while not chars.is_empty():
        reversed_string += chars.pop()

    return reversed_string
Exemplo n.º 7
0
def test_stack():
    f = Stack()

    test_array = [i for i in range(100)]

    for i in test_array:
        f.push(i)

    result = []

    while not f.is_empty():
        result.append(f.pop())
    test_array.reverse()
    assert test_array == result
Exemplo n.º 8
0
def dfs(graph: Graph, start_node: str, target_node: str, visited_nodes: set):
    stack = Stack()
    stack.push(start_node)

    while not stack.is_empty():
        current = stack.pop()
        if current == target_node:
            return True

        adj = graph.get_edges_node(current)
        for node in adj:
            if node not in visited_nodes:
                stack.push(node)
    return False
Exemplo n.º 9
0
class Calc:

    COUNT = 0
    # If there is a 'p' at the end of the expression. This will set to True and print the result
    PRINT = False

    def __init__(self):
        self.stack = Stack()
        self.COUNT = 0
        self.PRINT = False
        self.operators = ["+", "-", "*", "//", "n", "e"]
        self.form = Helper()

    def calculate(self, unformatted_expression):
        # format the expression correctly so it can be calculated
        expression = self.form.format_expression(unformatted_expression)

        # loop through the expression
        while len(expression) > self.COUNT:
            # Get the next item from the expression
            next_item = expression[self.COUNT]
            # count + 2, to skip the blank spaces
            self.COUNT += 2

            if next_item is "p":
                self.PRINT = True

            # add the numbers to the stack
            elif next_item not in self.operators:
                self.stack.push(next_item)

            else:
                # if an operator is found, pop the numbers
                try:
                    num1 = int(self.stack.pop())
                    if self.stack.is_empty() is False:
                        num2 = int(self.stack.pop())
                        # send to the calculation class and get the result
                        result = Helper.get_result(next_item, num1, num2)
                        # push the result to the stack
                        self.stack.push(result)
                    else:
                        result = Helper.get_result(next_item, num1)
                        self.stack.push(result)
                except ValueError:
                    print("Cannot calculate. Invalid Expression!")
                    return

        # if a print symbol is found. Print result to the terminal
        try:
            if self.stack.is_empty():
                raise ValueError
            if self.PRINT is True:
                print(self.stack.pop())
                # Reset the count and printing options so the method can be called again
                self.COUNT = 0
                self.PRINT = False
            else:
                self.COUNT = 0
                self.PRINT = False
                return self.stack.pop()
        except ValueError:
            print("Cannot calculate. Invalid Expression!")
            return
def test_stack_is_empty():
    stack = Stack()
    stack.push('a')
    stack.pop()

    assert stack.is_empty() is True