Пример #1
0
def post_to_pre(strs):
    s = strs.split()
    St = Stack()
    final = ""

    for value in s:

        if value in ['+', '-', '*', '/', '%']:

            a = St.Pop()
            b = St.Pop()
            final = str(value) + " " + str(b) + " " + str(a)
            St.Push(final)

        elif value.isalpha():
            St.Push(value)

        elif is_number(value):
            St.Push(value)

        else:
            print("Error")
            exit(0)

    return St.Top()
Пример #2
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    S = Stack()
    n = len(expr)

    for i in range(0, n):
        symb = expr[i]  #next symbol
        # print(symb)

        if symb in ['{', '(', '[']:
            S.Push(symb)

        elif symb in ['}', ')', ']']:

            if S.isEmpty():
                return False
            if S.Top() == '{' and symb == '}':
                S.Pop()
            elif S.Top() == '(' and symb == ')':
                S.Pop()
            elif S.Top() == '[' and symb == ']':
                S.Pop()

        else:
            continue

    if S.isEmpty():
        return True
    else:
        return False
Пример #3
0
def eval_prefix(strs):
    strs = reverse(strs)
    s = strs.split()
    St = Stack()
    count = 0

    for value in s:

        value = reverse(value)

        if value in ['+', '-', '*', '/', '%']:

            b = St.Pop()
            a = St.Pop()

            if value == '+':
                result = a + b
                St.Push(float(result))

            elif value == '-':
                result = a - b
                St.Push(float(result))

            elif value == '/':
                result = a / b
                St.Push(float(result))

            elif value == '*':
                result = a * b
                St.Push(float(result))

            elif value == '%':
                result = a % b
                St.Push(float(result))

        elif is_number(value):
            St.Push(float(value))

        else:
            print("Error")

    return St.Top()