天天看點

10以内計算python

class Stack:
    def __init__(self):#建立一個空
        self.items = []
    def isEmpty(self):#判斷傳回棧是否為空
        return self.items == []
    def push(self, item):#将一個item加入棧頂
        self.items.append(item)
    def pop(self):#檢視棧頂資料,看完後删除
        return self.items.pop()
    def peek(self):#檢視棧頂資料,但不對其做修改
        return self.items[len(self.items)-1]
    def size(self):#傳回棧中的資料個數
        return len(self.items)
def transform(string):
    compare = {}
    compare["*"] = 3
    compare["/"] = 3
    compare["+"] = 2
    compare["-"] = 2
    compare["("] = 1
    record_mark_stack = Stack()#儲存字元的棧
    output_stack= []#輸出數的數組
    # tokenList = string.split()#以空格為隔開符将表達式分為切片
    tokenList = list(string)
    print(tokenList)
    for token in tokenList:
        print('目前輪到',token)
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnobprstuvwxyz" or token in "0123456789":
            output_stack.append(token)#入數組
        elif token == '(':
            record_mark_stack.push(token)#入棧
        elif token == ')':
            topToken = record_mark_stack.pop()#出棧
            while topToken != '(':
                output_stack.append(topToken)#入數組
                topToken = record_mark_stack.pop()
        elif token == ' ':
                continue
        else:
            print('比較record_mark_stack和token的優先級',record_mark_stack.items,token)
            while (not record_mark_stack.isEmpty()) and \
               (compare[record_mark_stack.peek()] >= compare[token]):
                #record_mark_stack.peek()前面的數 token為後面的數
                    output_stack.append(record_mark_stack.pop())#成立則讓等級高的出棧
                    print(output_stack)
            record_mark_stack.push(token)#為了保證優先級的入棧,讓等級低的入棧
        print('每一次輸出數組out_stack的字元', output_stack)
        print('每一次入記錄棧 record_mark_stack的字元', record_mark_stack.items)
    print('最終的記錄棧 record_mark_stack',record_mark_stack.items)
    while not record_mark_stack.isEmpty():
        output_stack.append(record_mark_stack.pop())#把所有元素都轉到輸出數組中(相反性)
    return " ".join(output_stack)#将字元全連在一起

def Math(op, op1, op2):#計算規則
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2
def calculate(string):

    string_houzhui=transform(string)
    print('字尾數', string_houzhui)
    tokenList2 = list(string_houzhui)
    count_stack=Stack()
    print(tokenList2)
    for token in tokenList2:
        if token in '0123456789':
            # count_stack.push(token)
            count_stack.push(int(token))
        elif token==' ':
            continue
        else:
            op1=count_stack.pop()
            op2=count_stack.pop()
            result=Math(token,op1,op2)
            count_stack.push(result)
        print(count_stack.items)
    return count_stack.peek()

print('計算結果',calculate('4*5+1'))