2012-12-21 63 views
2

我試圖在列表中給出一定數量的python 2.7中的所有數字組合。嘗試itertool的組合,但無法完全弄清楚,所以在這裏。在python上查找所有可能的組合

mylist=[1,2,3,4,5,6,7,8,9,10] 
number=60 # for 3 elements 

results=[[3,4,5],[2,3,10],[2,5,6],[1,6,10]...] 

我試圖

import itertools 

num = [1, 2, 3, 4, 5,6,7,8,9,10] 
combinations = [] 

for combination in itertools.combinations(num, 3): 
    combinations.append(int("".join(str(i) for i in combination))) 
    print combinations 

# ... 
combination=[123,124,125....] 
+3

你想要所有的組合,當乘以60時,對嗎? – Scharron

+0

是的所有組合3哪個產品= 60 – user1921180

回答

3
import itertools 

num = [1, 2, 3, 4, 5,6,7,8,9,10] 
combinations = itertools.combinations(num, 3) 
matching = [c for c in combinations if reduce(lambda x, y: x * y, c, 1) == 60] 

print(matching) 

神奇的線是matching = [c for c in combinations if reduce(lambda x, y: x * y, c, 1) == 60]。這是一個列表解析,相當於:

matching = [] 
for c in combinations: 
    if reduce(lambda x, y: x * y, c, 1) == 60: 
    matching.append(c) 

您可以找到有關reduce功能here

+0

非常感謝Scharron。 – user1921180

+2

@ user1921180,如果你喜歡這個答案,請通過標記爲「正確」來獎勵Scharron。 –

+3

'reduce(operator.mul,c)'比'reduce(lambda x,y:x * y,c,1)'更好。 –

-1
>>> import itertools 
>>> numbers = 1,2,3,4,5,6,7,8,9 

>>> combinations = itertools.combinations(numbers,3) 

>>> ["".join([str(a),str(b), str(c)]) for a, b, c in combinations if a*b*c == 60] 
['256', '345'] 

這將有N組合工作所需

>>> import itertools, operator 
>>> numbers = 1,2,3,4,5,6,7,8,9,10 
>>> multiply_must_be = 60 

>>> combinations = itertools.combinations(numbers, 3) 

>>> combine = lambda arr: "".join([str(item) for item in arr]) 
>>> multiply = lambda arr: reduce(operator.mul, arr, 1) 

>>> [combine(combo) for combo in combinations if multiply(combo) == multiply_must_be] 
['1610', '2310', '256', '345'] 
0

雖然已經回答了文檔,這裏是一個遞歸算法來找到組合:

def findCombination(product, numList, length, minimum): 
    if length == 0 and product == 1: 
     return [[]] 
    if length == 1 and product in numList and product > minimum: 
     return [[product]] 

    ret = [] 
    subList = [item for item in numList if item > minimum] 
    for n in subList: 
     if product % n == 0: 
      temp = findCombination(product/n, subList, length - 1, n) 
      for x in temp: 
       ret += [[n] + x] 
    return ret 

要使其工作正常,mylist必須排序,因爲組合是按升序進行的。

>>> mylist=[1,2,3,4,5,6,7,8,9,10] 
>>> mylist = sorted(mylist) 
>>> number = 60 
>>> print findCombination(number, mylist, 3, mylist[0]) 
[[1, 6, 10], [2, 3, 10], [2, 5, 6], [3, 4, 5]]