私は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....]
回答:
回答№1の場合は3import 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
関数 ここに
回答№2の場合は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]]
回答№3の場合は-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"]