使用字典查找和递归的基本计算器

没有什么

请解释我

我想知道这个calculate函数是如何工作的。

from operator import pow, truediv, mul, add, sub  

operators = {
    '+': add,
    '-': sub,
    '*': mul,
    '/': truediv
}
    
def calculate(s):
    if s.isdigit():
        return float(s)
    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))
    
calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))
曾安

假设我们有 34 + 54:

from operator import pow, truediv, mul, add, sub  

operators = {
    '+': add,
    '-': sub,
    '*': mul,
    '/': truediv
}

def calculate(s):
    if s.isdigit(): # If s.isdigit() is True, that means the user only input a number, no operators, and so the program will only return that number
        return float(s)
    for c in operators.keys(): # For every key in the operators dictionary...
        left, operator, right = s.partition(c) # splitting the string at the operator to get a tuple: ('34','+','54')
        if operator in operators: # If the operator is in operators:
            return operators[operator](calculate(left), calculate(right)) # Call the value(function imported) for that key with the arguments, left (34) and right (54)

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章