如果我有这个简单的代码,我该如何显示所有可用的变体?
#Display all possible variants until reach input sum with coins of 2 and 5
#Not fixed: Output only first result !
#Input
summ = int(input("Enter sum: "))
two = 2
five = 5
#Calculations/Checks/Output
for i in range(0, two+1):
for j in range(0, five+1):
if (i*2 + j*5 == summ):
print(i, "*2 + ", j, "*5 = ", summ)
#End
例如:
Input: 17
Output:
1*2 + 3*5 = 17
6*2 + 1*5 = 17
但代码只显示第一个结果?
我该如何解决这个问题?
答案 0 :(得分:0)
更改range
的输入:
summ = int(input("Enter sum: "))
two = 2
five = 5
for i in range(summ//two+1):
for j in range(summ//five+1):
if (i*2 + j*5 == summ):
print(i, "* 2 +", j, "* 5 =", summ)
答案 1 :(得分:0)
您可以使用itertools和生成器:
In [17]: def correct_sum_i(i, val):
...: sum_perm = [comb for comb in itertools.combinations_with_replacement([2,5],i) if sum(comb) == val]
...: return sum_perm[0] if sum_perm else None
...:
In [18]: val = 14
In [19]: next(correct_sum_i(i,val) for i in range(1000) if correct_sum_i(i, val))
Out[19]: (2, 2, 5, 5)
编辑:您可能还想检查无法做到的病态情况,例如1,3等......
编辑:所有金额
In [50]: def all_sums(char_set, sum_value):
...: def correct_sum_i(i):
...:
...: sum_perm = [comb for comb in itertools.combinations_with_replacement(char_set,i) if sum(comb) == sum_value]
...: return sum_perm if sum_perm else None
...:
...: assert min(char_set) > 0
...:
...: return list(correct_sum_i(i) for i in range(int(sum_value / min(char_set))+ 1) if correct_sum_i(i))
...:
In [51]: print (all_sums([2,5], 20))
[[(5, 5, 5, 5)], [(2, 2, 2, 2, 2, 5, 5)], [(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)]]
这也为您提供了所需的行为:
In [53]: print (all_sums([2,5], 17))
[[(2, 5, 5, 5)], [(2, 2, 2, 2, 2, 2, 5)]]