使用字典查找和递归的基本计算器
Basic Calculator using Dictionary Lookup and Recursion
请解释一下
我想知道 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)))
请解释一下
我想知道 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)))