示例#1
0
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()
示例#2
0
def revstring(mystr):
    s = Stack()
    for c in mystr:
        s.push(c)
    revstr = ""
    while not s.is_empty():
        revstr += s.pop()
    return revstr
def divide_by_2(dec):
    s = Stack()
    while dec > 0:
        rem = dec % 2
        s.push(rem)
        dec = dec // 2
    bin = ""
    while not s.is_empty():
        bin += str(s.pop())
    return bin
示例#4
0
def base_converter(decimal_num, base):
    s = Stack()
    digits = "0123456789ABCDEF"
    while decimal_num > 0:
        rem = decimal_num % base
        s.push(rem)
        decimal_num = decimal_num // base
    new_str = ""
    while not s.is_empty():
        new_str += digits[s.pop()]
    return new_str
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
示例#6
0
def infix_to_postfix(infix_expr):
    prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    op_stack = Stack()
    postfix_list = []
    token_list = infix_expr.split()
    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfix_list.append(token)
        elif token == "(":
            op_stack.push(token)
        elif token == ")":
            top_token = op_stack.pop()
            while top_token != "(":
                postfix_list.append(top_token)
                top_token = op_stack.pop()
        else:
            while (not op_stack.is_empty()) and (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)
    while not op_stack.is_empty():
        postfix_list.append(op_stack.pop())
    return " ".join(postfix_list)