Itertools组合不会输出大于3的序列
在下面的代码中,如果输出的结果序列超过3个值,我就无法得到结果。这个代码什么都不返回,有没有办法让下面的代码返回正确的答案:7175.90、14259.90、11625.47和3764.81?
import itertools
from decimal import Decimal
# Original list of numbers (including decimals)
numbers = [7175.90, 14259.90, 11625.47, 3764.81, 1995.27, 542.23, 2038.32, 4048.83, 490.40, 1279.00, 3248.90]
# Convert the original numbers to Decimal format
#numbers = [Decimal(num) for num in original_numbers]
target_sum = 36826.08
# Generate all combinations of the numbers
result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == target_sum]
print(result)
4 个回答
1
你可以通过重建原始的书写形式来让 Decimal
正常工作:
# Convert the original numbers to Decimal format
numbers = [Decimal(str(num)) for num in numbers]
target_sum = Decimal(str(target_sum))
2
当我运行程序时,我得到了:
因为浮点运算的问题,你得到了一个空列表
浮点数运算有问题
for seq in itertools.combinations(numbers, 4):
print((seq),'-->',sum(seq))
(7175.9, 14259.9, 11625.47, 3764.81) --> 36826.079999999994
(7175.9, 14259.9, 11625.47, 1995.27) --> 35056.53999999999
(7175.9, 14259.9, 11625.47, 542.23) --> 33603.5
(7175.9, 14259.9, 11625.47, 2038.32) --> 35099.59
(7175.9, 14259.9, 11625.47, 4048.83) --> 37110.1
(7175.9, 14259.9, 11625.47, 490.4) --> 33551.67
(7175.9, 14259.9, 11625.47, 1279.0) --> 34340.27
(7175.9, 14259.9, 11625.47, 3248.9) --> 36310.17
(7175.9, 14259.9, 3764.81, 1995.27) --> 27195.88
(7175.9, 14259.9, 3764.81, 542.23) --> 25742.84
(7175.9, 14259.9, 3764.81, 2038.32) --> 27238.93
(7175.9, 14259.9, 3764.81, 4048.83) --> 29249.440000000002
(7175.9, 14259.9, 3764.81, 490.4) --> 25691.010000000002
.....
.....
检查一下你的值和你想要的值是否一致:
36826.079999999994 == 36826.08
#False
3
使用 math.isclose
函数 - 你在使用浮点数运算,这种运算并不是完全准确的:
import itertools
import math
# Original list of numbers (including decimals)
numbers = [
7175.90,
14259.90,
11625.47,
3764.81,
1995.27,
542.23,
2038.32,
4048.83,
490.40,
1279.00,
3248.90,
]
target_sum = 36826.08
# Generate all combinations of the numbers
result = [
seq
for i in range(len(numbers), 0, -1)
for seq in itertools.combinations(numbers, i)
if math.isclose(sum(seq), target_sum)
]
print(result)
输出结果是:
[(7175.9, 14259.9, 11625.47, 3764.81)]