2017年12月22日 星期五

a017: 五則運算


a017: 五則運算


計算五則運算式的結果,包含加、減、乘、除、餘



輸入一個字串,其中包含運算元及運算子,為了方便讀取,所有的運算子及運算元均以空格區隔。
運算元為 0 ~231 -1 的整數
運算子則包含 + - * / % 及 ( )
運算時請注意先乘除後加減及() 優先運算的計算規則


# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005
#
#stack.py

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, 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 infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

#==============================================
while True:
    print("輸入一個字串,其中包含運算元及運算子,為了方便讀取,")
    print("所有的運算子及運算元均以空格區隔。")
    print("範例輸入")
    print("2 + 3 * 4")
    print("2 * ( 3 + 4 ) * 5")

    strIn=str(input("> "))
    strOut=infixToPostfix(strIn)
          
    print("infixToPostfix=",strOut)

    str_in=strOut

    tokens = str_in.split(" ")
    stack = []

    if tokens[0] == "help" or tokens[0] == "?":
        print ("Post-fix calculator takes in post-fix formatted equations and evaluates them.")
        print ("Input should be formatted in such a way that the equation can be evaluated fully.")
        print ("Ex. \"1 2 + 4 *\" equals \"12\"")

    elif tokens[0] == "quit" or tokens[0] == "q":
        break

    else:
        while len(tokens) > 0:
            item = tokens.pop(0)

            if item.isdigit():
                stack.append(int(item))

            elif item == "+":
                if len(stack) > 1:
                    stack.append(stack.pop() + stack.pop())
                else:
                    #ERROR
                    print ("ERROR: Invalid expression. Not enough input.")
                    break

            elif item == "-":
                if len(stack) > 1:
                    tmp = stack.pop()
                    stack.append(stack.pop() - tmp)
                else:
                    #ERROR
                    print ("ERROR: Invalid expression. Not enough input.")
                    break

            elif item == "*":
                if len(stack) > 1:
                    stack.append(stack.pop() * stack.pop())
                else:
                    #ERROR
                    print ("ERROR: Invalid expression. Not enough input.")
                    break

            elif item == "/":
                if len(stack) > 1:
                    tmp = stack.pop()
                    stack.append(stack.pop() / tmp)
                else:
                    #ERROR
                    print ("ERROR: Invalid expression. Not enough input.")
                    break

            elif item == "^":
                if len(stack) > 1:
                    tmp = stack.pop()
                    stack.append(pow(stack.pop(), tmp))
                else:
                    #ERROR
                    print ("ERROR: Invalid Expression. Not enough input.")
                    break

            else:
                #ERROR
                break

        print (stack.pop())



===================== RESTART: F:/Python_APSC/a017-4.py =====================
輸入一個字串,其中包含運算元及運算子,為了方便讀取,
所有的運算子及運算元均以空格區隔。
範例輸入
2 + 3 * 4
2 * ( 3 + 4 ) * 5
> 2 * ( 3 + 4 ) * 5
infixToPostfix= 2 3 4 + * 5 *
70
輸入一個字串,其中包含運算元及運算子,為了方便讀取,
所有的運算子及運算元均以空格區隔。
範例輸入
2 + 3 * 4
2 * ( 3 + 4 ) * 5
> 34 - 5 / 7 * 8
infixToPostfix= 34 5 7 / 8 * -
28.285714285714285
輸入一個字串,其中包含運算元及運算子,為了方便讀取,
所有的運算子及運算元均以空格區隔。
範例輸入
2 + 3 * 4
2 * ( 3 + 4 ) * 5

沒有留言:

張貼留言

2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2

 2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2 AngularJS 實例 <!DOCTYPE html> <html> <head> &...