def infix_to_postfix(expression):
    operator_stack = Stack()
    output = []
    token_list = expression.split()
    precedence = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}

    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    for token in token_list:
        try:
            int(token)
            number = True
        except ValueError:
            number = False
        if token in chars or number:
            output.append(token)
        elif token == "(":
            operator_stack.add(token)
        elif token == ")":
            stack_token = operator_stack.pop()
            while stack_token != "(":
                output.append(stack_token)
                stack_token = operator_stack.pop()
        else:
            while (not operator_stack.is_empty()) and \
                    (precedence[operator_stack.peek()] >= precedence[token]):
                output.append(operator_stack.pop())
            operator_stack.add(token)

    while not operator_stack.is_empty():
        output.append(operator_stack.pop())

    return " ".join(output)
예제 #2
0
def base_converter(number, base):
    num_stack = Stack()
    values = "0123456789ABCDEFGHIJKLMOPQ"

    while number > 0:
        num_stack.add(number % base)
        number = number // base

    converted_number = ""
    while not num_stack.is_empty():
        converted_number += values[num_stack.pop()]

    return converted_number
예제 #3
0
def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.add(e_tree)
    current_tree = e_tree
    for i in fp_list:
        if i == '(':
            current_tree.insert_left('')
            p_stack.add(current_tree)
            current_tree = current_tree.get_left_child()
        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.set_root_val(int(i))
            parent = p_stack.pop()
            current_tree = parent
        elif i in ['+', '-', '*', '/']:
            current_tree.set_root_val(i)
            current_tree.insert_right('')
            p_stack.add(current_tree)
            current_tree = current_tree.get_right_child()
        elif i == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree