Exemple #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()
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()
Exemple #3
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()
Exemple #4
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()
Exemple #5
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
Exemple #6
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
Exemple #7
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
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
Exemple #10
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
Exemple #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()
        print(operand_stack.is_empty())
        if operand_stack.is_empty() is False:
            raise StackError("Stack is not empty")
        return answer
    except IndexError:
        raise StackError("Stack is empty") from IndexError
Exemple #12
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
my_list.add(17)
my_list.add(93)
my_list.add(26)
my_list.add(54)

print(my_list.size())
print(my_list.search(93))
print(my_list.search(100))

# 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")