在python上找到所有可能的组合

时间:2012-12-21 10:21:56

标签: python

我试图在列表中找到所有数字组合,在python 2.7上给出一定的数字。迭代的组合但是不能很好地解决它,所以在这里。

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 个答案:

答案 0 :(得分: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

的文档

答案 1 :(得分: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]]

答案 2 :(得分:-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']