2015-07-19 76 views
1

基本上这是一个组合程序。它汇总了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) 
+1

您的代码是否工作?它在做什么,它不应该?它应该怎么做呢?你的问题是什么,请具体说明一下?请为示例输入包含所需的和实际的输出。 – wwii

回答

0

的主要问题是,该程序的逻辑不适用于这种形式。

sum(item[1] for item in com)的最大值为30,则循环结束。因此,功能matchesyield什么。