2 回答
TA贡献1847条经验 获得超11个赞
要将算术运算符号转换为 python 函数,您可以使用dict它将符号与operator模块中的函数匹配:
import operator
operations_map = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
要处理整数和运算符列表,您可以使用 next 函数:
def process(numbers, operations):
if len(numbers) - 1 != len(operations):
raise ValueError(f"There're {len(numbers)} numbers and {len(operations)} operations.")
result = numbers[0]
for i in range(1, len(numbers)):
if operations[i - 1] in operations_map:
result = operations_map[operations[i - 1]](result, numbers[i])
else:
raise ValueError(f"\"{operations[i - 1]}\" is not valid operation.")
return result
用法:
process([50, 10, 20, 30, 40], ["+", "-", "+", "+"])
要查找结果最接近零的操作序列,您可以使用生成运算符的排列itertools.permutations()并使用以下方法查找最小结果min():
from itertools import permutations
def closest_to_zero(numbers, operations):
return min(
((process(numbers, current), tuple(current)) for current in permutations(operations)),
key=lambda x: abs(x[0])
)
value, chain = closest_to_zero([50, 10, 20, 30, 40], ["+", "-", "+", "+"])
要从一组可能的运算符中获取所有可能的组合,您可以使用itertools.product(),其中repeat参数将设置为len(numbers) - 1:
from itertools import product
def closest_to_zero_patched(numbers, operations):
return min(
((process(numbers, current), tuple(current)) for current in
product(operations, repeat=len(numbers) - 1)),
key=lambda x: abs(x[0])
)
value, chain = closest_to_zero_patched([50, 10, 20, 30, 40], {"+", "-"})
TA贡献1779条经验 获得超6个赞
如果你想要一个近乎单一的班轮(不一定是最有效的班轮):
您可以使用Truefor+和Falsefor对运算符列表进行编码,并为列表的第一个元素-添加一个附加值(如果您总是希望添加此元素),以便您的列表如下所示:Truels1 = [-,-,-,+]
s1 = [True, False, False, False, True]
然后使用包中的compress函数itertools你得到你的结果:
from itertools import compress
sum(compress(l, s1)) - sum(compress(l, [not i for i in s1]))
它本质上首先将与 's 关联的所有元素相加+,然后减去与-'s 关联的所有元素。
添加回答
举报
