基本上,这是一个组合程序。它对dict1中的所有值求和,并返回所有加到100的组合键。我希望得到相同的结果,但我不希望某些键/值在同一个组合组中。例如,我不希望密钥'a‘在任何带有密钥'b’的组合组中,密钥'c‘不在任何带有'd’的组合组中,等等。
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)发布于 2015-07-20 07:16:45
主要的问题是,程序的逻辑不能以这种形式工作。
sum(item[1] for item in com)的最大值是30,然后循环结束。因此,函数matches不会yield任何东西。
https://stackoverflow.com/questions/31506242
复制相似问题