I need to generate combinations and limit the output to certain combos which meet a numeric criteria associated with the combo. Here are the codes:
import itertools
mylist = [('Beef', 1), ('Pepper', -1),('Onion', 6), ('Green', -1), ('Chicken', 4)]
lst = [item[0] for item in mylist]
combo = []
for i in range(1, 5):
for tpl in itertools.combinations(lst, i):
combo.append(tpl)
print(combo)
The code currently generates all possible combinations. I need to limit the result to only those combos where the value is certain numeric value. For example, if my value is 9, then the combo should be generated using "Onion", "Green", and "Chicken", or "Onion", "Chicken", and "Pepper". Because their numeric value adds up to 9 (6+4-1=9
). In this case, beef is excluded from the combo generation. How can I do that?