【问题标题】:Need to evaluate a mathematical expression using a For loop需要使用 For 循环计算数学表达式
【发布时间】:2022-01-21 05:02:12
【问题描述】:

我已经为一个接受字符串输入的计算器准备了这段代码:

keepAsking = True
equationList = []

while keepAsking:  # keep looping until keepAsking is false
    print("Please enter the mathematical expression you want the program to evaluate: \n")  # taking user input
    userInput = input()
    equationList.append(userInput)
    print("Do you have other operations to add? \n")  # another user input (choice)
    userChoice = input()
    if userChoice.lower() == "yes":  # if the user wants to keep asking
        keepAsking = True
    else:
        print(100*"-")
        print("|{0:<15s}|{1:^40s}|{2:>40s}|".format("Operation no.", "operation expression", "operation output"))
        # if not print the following
        print(100*"-")
        # For each equation get index and the item itself
        for i, item in enumerate(equationList):
            # evaluate executes python code
            print("|{0:<15d}|{1:^40s}|{2:>40.2f}|".format(i + 1, item, eval(item)))
        keepAsking = False
        print(100*"-")

但是我想用 For 循环替换 eval() 函数来评估表达式并产生相同的结果,这可能吗?

【问题讨论】:

  • 我看不出这个程序是如何工作的。就像如果有人说1*2 作为他们的第一个输入然后yes 然后*3 它会导致错误,所以也许不是说要添加的操作,你可能会再次说数学表达式......如果你想解析字符串自己来评估它当然是可能的。 nerdparadise.com/programming/parsemathexpr

标签: python loops eval calculator


【解决方案1】:

你可以试试这个:

def calc(expr): return sum([sub([mul([div(x) 
    for x in x]) 
    for x in x]) 
    for x in parse(expr)])
# -- calc--         This function will flatten each list
#                   into a number in correct mathematical order.


def parse(expr, syms=['+','-','*','/']): return [
    parse(x, syms[1:]) for x in expr.split(syms[0])
] if syms else float(expr)
# -- parse --       This function will transform the input string
#                   into a nested tree of numbers (in the 4th branch.)


def div(xs): return div(xs[:-1])/xs[-1] if len(xs) > 1 else xs[0]
def mul(xs): return mul(xs[1:])*xs[0] if xs else 1
def sub(xs): return xs[0]-sum(xs[1:])
# -- div/mul/sub -- These functions will do calculation on
#                   lists in each eg [1,2,3] will be handled like 1-2-3 = -4


if __name__ == '__main__': print(calc("100+1/2*2-1+3"))
# -- test           This test will calculate the string 100+1/2*2-1+3
#                   and the output will be 103.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2012-04-29
    • 1970-01-01
    • 2021-10-23
    • 2017-02-08
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多