这里是一个解决方案,如果你想考虑的情况下,你可以扔掉美分,或者你可以四舍五入到最接近的整数。这个要求把一个简单的解决方案变成了一个非常复杂的解决方案为了解释上述要求,我扩展了每个号码以包括额外的可能情况。展开的列表显示了新的名单,以获得组合:
import math
import itertools as it
tolerance = 150
target_sum = 8392
found = False
lis = [497.96, 10, 5084, 156.43, 381.3, 3298.85, 625.68]
def add_throw_and_round(num):
num_list = [num]
if int(num) != float(num):
num_list.append(math.floor(num))
if round(num) not in num_list:
num_list.append(round(num))
return sorted(num_list)
lis_expanded = map(add_throw_and_round, lis)
print "Expanded list:\n", lis_expanded, "\n\nTarget sum:\n", target_sum, "\n"
for n in range(1,len(lis) + 1): # n is number of summands in pick
lis_combos = it.combinations(lis_expanded, n)
for lis_combo_n in lis_combos:
for combo_n in (it.product(*lis_combo_n)):
sum_ = sum(combo_n)
if sum_ == target_sum:
found = True
answer = combo_n
if sum_ > target_sum - tolerance and sum_ < target_sum + tolerance:
print "sum:", sum_, "\tCombination: ", combo_n
if found:
print "\nThere is a match: ", answer
else:
print "\nNo exact match found"
所以我决定以表明是内部目标总的150,只是为了看看它工作的所有款项。目前还没有比赛是总和正好是8276:
>>>
===== RESTART: C:/Users/Joe/Desktop/scripts/Stack_overflow/cents_py2.py =====
Expanded list:
[[497.0, 497.96, 498.0], [10], [5084], [156.0, 156.43], [381.0, 381.3], [3298.0, 3298.85, 3299.0], [625.0, 625.68, 626.0]]
Target sum:
8276
sum: 8382.0 Combination: (5084, 3298.0)
sum: 8382.85 Combination: (5084, 3298.85)
sum: 8383.0 Combination: (5084, 3299.0)
sum: 8392.0 Combination: (10, 5084, 3298.0)
sum: 8392.85 Combination: (10, 5084, 3298.85)
sum: 8393.0 Combination: (10, 5084, 3299.0)
No exact match found
>>>
注意上面它测试,其中美分被抛出,并四舍五入的情况。 只是为了测试当目标总和是否匹配时它会报告匹配,我尝试了target_sum = 8392,因为输出显示一个组合应该匹配它。所以这里是这种情况下的输出:
>>>
===== RESTART: C:/Users/Joe/Desktop/scripts/Stack_overflow/cents_py2.py =====
Expanded list:
[[497.0, 497.96, 498.0], [10], [5084], [156.0, 156.43], [381.0, 381.3], [3298.0, 3298.85, 3299.0], [625.0, 625.68, 626.0]]
Target sum:
8392
sum: 8382.0 Combination: (5084, 3298.0)
sum: 8382.85 Combination: (5084, 3298.85)
sum: 8383.0 Combination: (5084, 3299.0)
sum: 8392.0 Combination: (10, 5084, 3298.0)
sum: 8392.85 Combination: (10, 5084, 3298.85)
sum: 8393.0 Combination: (10, 5084, 3299.0)
sum: 8538.0 Combination: (5084, 156.0, 3298.0)
sum: 8538.85 Combination: (5084, 156.0, 3298.85)
sum: 8539.0 Combination: (5084, 156.0, 3299.0)
sum: 8538.43 Combination: (5084, 156.43, 3298.0)
sum: 8539.28 Combination: (5084, 156.43, 3298.85)
sum: 8539.43 Combination: (5084, 156.43, 3299.0)
There is a match: (10, 5084, 3298.0)
>>>
您是否需要保留号码列表中的号码顺序? – thiruvenkadam
我们可以使用数字“n”次吗?因为,如果我们只能使用一次数字,8276就无法通过输入设置到达。 – thiruvenkadam
嗨,超级,因为你提到的圆角的洞察力也是你想要的,我发布了一个解决方案来显示任意数量的最接近匹配。请说明,如果这是你的意思,或者你只是想要一个*完全匹配*。后者在你的例子中没有输出。 –