简体   繁体   中英

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.

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 . 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. The functions in itertools are, as the name of the module suggests, iterators. 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.

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'),
 #  .... ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM