[英]How to find possible combination of keys having sum of values equal or greater than k using dictionary in Python?
d1= {"Noodles":20, "Burger":10, "Sandwitch":20}
d2= {"Pepsi": 20, "Coke": 25, "Soup": 15, "Sprite":10}
dic = {**d1, **d2}
keys = dic.keys()
import itertools
all_comb = list(itertools.combinations(keys, 4))
for val in all_comb:
lt = list(val)
sum = dic[lt[0]] + dic[lt[1]] + dic[lt[2]] + dic[lt[3]]
if sum < 70:
all_comb = all_comb.remove(val)
else:
continue
print(all_comb)
This code is displaying all the combination of keys, I want to display only the combinations having a sum of 70 or greater.此代码显示所有键组合,我只想显示总和为 70 或更大的组合。
The main problem is that you remove items from the list while iterating on it.主要问题是您在迭代列表时从列表中删除了项目。 As a general rule, don't do that, you're going to miss items.
作为一般规则,不要这样做,你会错过项目。 You should rather build a new list.
您应该构建一个新列表。
In your case, it is better to only keep the valid combinations while you iterate on the output of itertools.combinations
.在您的情况下,最好在迭代
itertools.combinations
的输出时仅保留有效组合。 You should not use list(itertools.combinations(...))
: this forces all possible combinations to be calculated and stored immediately, which you don't need, and is inefficient.您不应该使用
list(itertools.combinations(...))
:这会强制立即计算和存储所有可能的组合,这是您不需要的,而且效率低下。 The functions in itertools
are, as the name of the module suggests, iterators.正如模块名称所暗示的那样,
itertools
中的函数是迭代器。 They generate their output values lazily, one by one.他们一个接一个地懒惰地生成输出值。
Just do:做就是了:
for combination in itertools.combinations(...):
# check the combination and store it if valid
As a side note, avoid using the names of Python builtin functions (like sum
) as variable names, as this shadows the original functions.作为旁注,避免使用 Python 内置函数的名称(如
sum
)作为变量名称,因为这会影响原始函数。
So, your code could be:所以,你的代码可能是:
import itertools
d1= {"Noodles":20, "Burger":10, "Sandwitch":20}
d2= {"Pepsi": 20, "Coke": 25, "Soup": 15, "Sprite":10}
dic = {**d1, **d2}
keys = dic.keys()
valid_combinations = []
for comb in itertools.combinations(keys, 4):
total = sum(dic[key] for key in comb)
if total >= 70:
valid_combinations.append(comb)
print(valid_combinations)
# [('Noodles', 'Burger', 'Sandwitch', 'Pepsi'),
# ('Noodles', 'Burger', 'Sandwitch', 'Coke'),
# ('Noodles', 'Burger', 'Pepsi', 'Coke'),
# ('Noodles', 'Burger', 'Coke', 'Soup'),
# .... ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.