是否有数学函数可以加、减、乘、幂或,并且可以对传递给函数的多个元素起作用?
Are there mathematical functions to add, substract, multiply, power, or, and that works on multiple elements passed to fuction?
该函数应采用多个参数并对它们进行某些数学运算(+、-、*、**、|、&)。 + 是默认运算符。数学函数连接到字典。以下是我到目前为止所做的。但我对数学运算有疑问(不要使用多个参数)。谁能帮忙?
例子 args: 1, 3, 5, operation='-' --> result: 1 - 3 - 5 = -7
def multi_calculator(*args: int, operation='+'):
import operator
ops = {
'+': sum,
'-': operator.sub,
'*': operator.mul,
'**': operator.pow,
'|': operator.or_,
'&': operator.and_,
}
if operation not in ops:
result = 'Unknown operator'
elif len(args) == 0:
result = 0
elif len(args) == 1:
result = args[0]
else:
result = ops[operation](args)
return result
print(multi_calculator(1, 2, 3, operation='-'))
您可以使用 functools.reduce
:
import operator
import functools
def multi_calculator(*args: int, operation='+'):
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'**': operator.pow,
'|': operator.or_,
'&': operator.and_,
}
if operation not in ops:
result = 'Unknown operator'
elif len(args) == 0:
result = 0
elif len(args) == 1:
result = args[0]
else:
result = functools.reduce(ops[operation], args)
return result
print(multi_calculator(1, 2, 3, operation='-'))
该函数应采用多个参数并对它们进行某些数学运算(+、-、*、**、|、&)。 + 是默认运算符。数学函数连接到字典。以下是我到目前为止所做的。但我对数学运算有疑问(不要使用多个参数)。谁能帮忙? 例子 args: 1, 3, 5, operation='-' --> result: 1 - 3 - 5 = -7
def multi_calculator(*args: int, operation='+'):
import operator
ops = {
'+': sum,
'-': operator.sub,
'*': operator.mul,
'**': operator.pow,
'|': operator.or_,
'&': operator.and_,
}
if operation not in ops:
result = 'Unknown operator'
elif len(args) == 0:
result = 0
elif len(args) == 1:
result = args[0]
else:
result = ops[operation](args)
return result
print(multi_calculator(1, 2, 3, operation='-'))
您可以使用 functools.reduce
:
import operator
import functools
def multi_calculator(*args: int, operation='+'):
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'**': operator.pow,
'|': operator.or_,
'&': operator.and_,
}
if operation not in ops:
result = 'Unknown operator'
elif len(args) == 0:
result = 0
elif len(args) == 1:
result = args[0]
else:
result = functools.reduce(ops[operation], args)
return result
print(multi_calculator(1, 2, 3, operation='-'))