2

我正在尝试在 python 2.7 上给出特定数字的列表中找到所有数字组合。尝试了 itertool 的组合,但无法完全弄清楚,所以就在这里。

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....]
4

3 回答 3

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功能的文档

于 2012-12-21T10:27:47.957 回答
0

Though it has been answered, here's a recursive algorithm to find combinations:

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

To make it work correctly, mylist has to be sorted, because the combinations are made in ascending order.

>>> 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]]
于 2012-12-21T12:17:20.830 回答
-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']
于 2012-12-21T10:24:06.930 回答