Basically this is a combination program. It sums up all values in dict1 and returns all key combinations that add to 100. I want to get the same result, but I don't want certain key/values to be in the same combination group. ie I don't want key 'a' to be in any combination group with key 'b', key 'c' not be in any combination group with 'd', etc.
import itertools
dict1 = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'f':8}
def matches(d, target):
# First try single items, then couples, then triplets etc.
for num in range(1,len(d)+1):
# Iterate over all possible combinations of length num
for com in itertools.combinations(d.items(), num):
# Does the sum of all second items per key/value pair match the target?
if sum(item[1] for item in com) == target:
# Yield one item at a time, so the caller can decide when to stop
yield dict(com).keys()
for match in matches(dict1, 100):
print(match)
The main problem is, that the logic of the program doesn't work in this form.
The maximum of sum(item[1] for item in com)
is 30
, then the loops end. Thus function matches
doesn't yield
anything.
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.