Exemple #1
0
    def parse(self, exp: str) -> None:

        stack = Stack()
        tokens = math_exp_parser.tokenize_cumulatively(exp)

        current_tree: ExpParseTree = self
        stack.push(self)

        for t in tokens:
            if t == "(":  # insert a child to the left and move there
                current_tree.insert_left(t)
                stack.push(current_tree)
                current_tree = current_tree.left
            elif t == ")":  # move up to parent
                current_tree = stack.pop()
            elif t in [
                    "+",
                    "-",
                    "*",
                    "/",
            ]:  # set the operator for root, insert a child to the right and move there
                current_tree.key = t
                new_node = current_tree.insert_right(t)
                stack.push(current_tree)
                current_tree = current_tree.right
            else:  # set the value to the current tree's root and move up to parent
                current_tree.key = t
                current_tree = stack.pop()
Exemple #2
0
def test_push_pop():
    s = Stack()
    s.push(6)
    assert s.pop() == 6
    s.push(9)
    s.push(15)
    assert s.pop() == 15
    assert s.pop() == 9
def reverse_str(input: str) -> str:
    """Reverses a string using a Stack data structure.
    
    Arguments:
        input {str} -- string to reverse
    
    Returns:
        str -- reversed string
    """
    stack = Stack()
    for c in input:
        stack.push(c)
    return "".join([stack.pop() for c in range(len(stack))])
Exemple #4
0
def balanced_parantheses(input: str) -> bool:
    """Checks if a given string has balanced opening and closing parantheses, i.e "(" and ")"
    
    Arguments:
        input {str} -- Input string to check
    
    Returns:
        bool -- True if balanced, False otherwise
    """
    stack = Stack()
    if len(input) == 0:
        return True
    for c in input:
        if c == "(":
            stack.push(c)
        elif c == ")":
            # the stack shouldn't be empty when we see a closing parantheses
            if stack.is_empty():
                return False
            stack.pop()

    return stack.is_empty()
Exemple #5
0
def test_pop_empty_raiseserror():
    s = Stack()
    with pytest.raises(Exception) as e:
        assert s.pop()
    assert str(e.value) == Stack.EMPTY_STACK_ERR_MSG
Exemple #6
0
def test_peek():
    s = Stack()
    s.push("jim jarmusch")
    s.push("mike leigh")
    s.push("tony gatlif")
    assert s.peek() == "tony gatlif"
    s.pop()
    assert s.peek() == "mike leigh"
    s.push("zeki demirkubuz")
    assert s.peek() == "zeki demirkubuz"
Exemple #7
0
def test_len():
    s = Stack()
    s.push(6)
    s.pop()
    assert len(s) == 0
    s.push(9)
    s.push(15)
    s.pop()
    assert len(s) == 1
    s.push(21)
    assert len(s) == 2