Ejemplo n.º 1
0
def par_checker_ext(line):
    """Check if parentheses & brackets are balanced"""
    stack = Stack()
    balanced = True
    i = 0
    while i < len(line) and balanced:
        symbol = line[i]
        if symbol in "( { [ <":
            stack.push(symbol)
        else:
            if stack.is_empty():
                balanced = False
            else:
                sym2 = (
                    symbol.replace(")", "(")
                    .replace("]", "[")
                    .replace("}", "{")
                    .replace(">", "<")
                )
                if sym2 == stack.peek():
                    stack.pop()
                else:
                    balanced = False
        i = i + 1
    return balanced and stack.is_empty()
Ejemplo n.º 2
0
def postfix_eval(postfix_expr: str) -> int:
    """Evaluate an expression"""
    operand_stack = Stack()
    token_list = postfix_expr[:-2].split()

    for token in token_list:
        # if token in "0123456789":
        try:
            if isinstance(int(token), int):
                operand_stack.push(int(token))
        except ValueError:
            if token in ("+", "-", "*", "/", "%", "//", "**"):
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token, operand1, operand2)
                operand_stack.push(result)
            else:
                raise TokenError(f"Unknown token: {token}")
    try:
        answer = operand_stack.pop()
    except IndexError:
        raise StackError("Stack is empty") from IndexError

    if not operand_stack.is_empty():
        raise StackError("Stack is not empty")

    return answer
Ejemplo n.º 3
0
def postfix_eval(postfix_expr: str) -> int:
    """ evaluate postfix expressions in a string """
    operandStack = Stack()
    tokenList = postfix_expr.split()
    try:
        for token in tokenList:
            if token.isnumeric():
                operandStack.push(int(token))
            elif token in "* ** / // % + -":
                ## this if statement is not working - why not?
                if operandStack.size() < 2:
                    raise SyntaxError("invalid syntax")
                else:
                    operand2 = operandStack.pop()
                    operand1 = operandStack.pop()
                    result = do_math(token, operand1, operand2)
                    operandStack.push(result)
            elif token == "=":
                if operandStack.size() > 1:
                    raise StackError("Stack is not empty")
                elif operandStack.size() == 0:
                    raise StackError("Stack is empty")
                else:
                    return operandStack.pop()
            else:
                raise TokenError(f"Unknown token: {token}")
    except ZeroDivisionError as err:
        raise ZeroDivisionError(f"{err}")
    except SyntaxError:
        raise SyntaxError(f"Invalid syntax")
    except TokenError as err:
        raise TokenError(f"{err}")
Ejemplo n.º 4
0
def rpn_calc(postfix_expr):
    """Evaluate a postfix expression"""

    operandStack = Stack()
    tokenList = postfix_expr.split()
    try:
        for token in tokenList:
            if token in "0123456789":
                operandStack.push(int(token))
            elif token in "+-*/":
                if operandStack.size() < 2:
                    raise StackError("Stack is empty")
                else:
                    operand2 = operandStack.pop()
                    operand1 = operandStack.pop()
                    result = doMath(token, operand1, operand2)
                    operandStack.push(result)
            else:
                raise TokenError(f"Unknown token: {token}")
        if operandStack.size() > 1:
            raise StackError("Stack is not empty")

    except TokenError as err:
        raise TokenError(f"{err}")
    except SyntaxError:
        raise SyntaxError("Invalid syntax")
    except StackError as err:
        raise StackError(f"{err}")
    else:
        return operandStack.pop()
def par_checker(symbol_string):
    s = Stack()
    for symbol in symbol_string:
        if symbol == "(":
            s.push(symbol)
        else:
            if s.is_empty():
                return False
            else:
                s.pop()

    return s.is_empty()
Ejemplo n.º 6
0
def par_checker(line):
    """Textbook implementation"""
    stack = Stack()
    balanced = True
    i = 0
    while i < len(line) and balanced:
        symbol = line[i]
        if symbol == "(":
            stack.push(symbol)
        else:
            if stack.is_empty():
                balanced = False
            else:
                stack.pop()
        i = i + 1
    return balanced and stack.is_empty()
Ejemplo n.º 7
0
def rev_string(my_str):
    """Reverse characters in a string using a stack"""
    stack = Stack()
    rev_str = ''
    for i in my_str:
        stack.push(i)
    while stack.is_empty() is False:
        rev_str += stack.pop()
    return rev_str
Ejemplo n.º 8
0
def rev_string(my_str):
    """Reverse characters in a string using a stack"""
    char_stack = Stack()
    for char in my_str:
        char_stack.push(char)
    new_chars = []
    while char_stack.size() > 0:
        new_chars.append(char_stack.pop())
    new_str = "".join(str(char) for char in new_chars)
    return new_str
Ejemplo n.º 9
0
def rev_string(my_str):
    tmpStack = Stack()
    revStr = ""

    for ch in my_str:
        tmpStack.push(ch)

    while not tmpStack.is_empty():
        revStr = revStr + str(tmpStack.pop())

    return revStr
def to_str(n, base):
    r_stack = Stack()
    convert_string = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            r_stack.push(convert_string[n])
        else:
            r_stack.push(convert_string[n % base])
        n = n // base
    res = ""
    while not r_stack.is_empty():
        res = res + str(r_stack.pop())
    return res
Ejemplo n.º 11
0
def rpn_calc(postfix_expr):
    """Evaluate a postfix expression"""
    operand_stack = Stack()
    token_list = postfix_expr.split()

    try:
        for token in token_list:
            if token in "0123456789":
                operand_stack.push(int(token))
            elif token in "+-*/":
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token, operand1, operand2)
                operand_stack.push(result)
            else:
                raise TokenError(f'Unknown token: {token}')
        answer = operand_stack.pop()
        if operand_stack.is_empty() is False:
            raise StackError("Stack is not empty")
        return answer
    except IndexError:
        raise StackError("Stack is empty") from IndexError
Ejemplo n.º 12
0
def balance_checker(symbol_string):
    s = Stack()
    for symbol in symbol_string:
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.is_empty():
                return False
            else:
                if not matches(s.pop(), symbol):
                    return False

    return s.is_empty()
def base_converter(decimal_num, base):
    digits = "0123456789ABCDEF"
    rem_stack = Stack()

    while decimal_num > 0:
        rem = decimal_num % base
        rem_stack.push(rem)
        decimal_num = decimal_num // base

    new_string = ""
    while not rem_stack.is_empty():
        new_string = new_string + digits[rem_stack.pop()]

    return new_string
Ejemplo n.º 14
0
def par_checker_ext(line):
    """Check if parentheses are balanced"""
    stack = Stack()
    lefts = "([{<"
    rights = ")]}>"
    for i in line:
        if i in "([{<":
            stack.push(i)
        else:
            if stack.is_empty():
                return False
            if lefts.index(stack.pop()) != rights.index(i):
                return False
    return True
Ejemplo n.º 15
0
def base_converter(dec_num, base):
    """Convert a decimal number to any base"""
    if base not in [2, 8, 16]:
        raise ValueError(f'Cannot convert to base {base}.')

    digits = "0123456789ABCDEF"
    remains = Stack()

    while dec_num > 0:
        rem = dec_num % base
        remains.push(rem)
        dec_num = dec_num // base

    output = ''
    while not remains.is_empty():
        output += digits[remains.pop()]

    return output
Ejemplo n.º 16
0
def base_converter(dec_num, base):
    """Convert a decimal number to any base"""
    digits = "0123456789ABCDEF"
    remstack = Stack()
    try:
        if base in (2, 8, 16):
            while dec_num > 0:
                rem = dec_num % base
                remstack.push(rem)
                dec_num = dec_num // base
            new_string = ""
            ctr = remstack.size()
            while ctr > 0:
                new_string = new_string + digits[remstack.pop()]
                ctr -= 1
            return new_string
        else:
            raise BaseError
    except BaseError:
        print("Invalid base:  only 2, 8, or 16 may be used")
# Alternative implementation from the pythonds3 library
# -> sudo pip3 install pythonds3
from pythonds3.basic import Stack

s = Stack()

print(s.is_empty())
s.push(4)
s.push("dog")
print(s.peek())
s.push(True)
print(s.size())
print(s.is_empty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())

m = Stack()
m.push("x")
m.push("y")
m.push("z")

while not m.is_empty(): 
    print(m.peek())
    m.pop()

q = Queue()
q.enqueue(4)
q.enqueue("dog")