![](/img/trans.png)
[英]How to get all mathematical combinations of a list that equal a result number in Python
[英]how to get all combinations between 1 2 3 4 5 6 7 8 using each number once python
首先我想通知你我對python一無所知。 我試圖通過搜索一些初學者教程來了解基礎知識,但我什至無法理解這些。
因為我有一個非常具體的事情我想產生我希望這里有人可以幫助我。
我需要數字 1,2,3,4,5,6,7,8 之間的所有可能組合,第一個和最后一個數字必須始終為 1,並且這些數字不能使用兩次。
例如:
1 2 3 4 5 6 7 8 1 -
1 2 3 4 5 6 8 7 1 -
1 2 3 4 5 7 8 6 1 -
1 2 3 4 5 7 6 8 1 -
1 2 3 4 5 8 6 7 1 -
1 2 3 4 5 8 7 6 1 -
等等 :)
您想要數字 2 到 8 的排列,然后只需添加 1:
from itertools import permutations
for combo in permutations(range(2, 9)):
combo = (1,) + combo + (1,)
print(combo)
演示:
>>> from itertools import permutations
>>> for combo in permutations(range(2, 9)):
... combo = (1,) + combo + (1,)
... print(combo)
...
(1, 2, 3, 4, 5, 6, 7, 8, 1)
(1, 2, 3, 4, 5, 6, 8, 7, 1)
(1, 2, 3, 4, 5, 7, 6, 8, 1)
(1, 2, 3, 4, 5, 7, 8, 6, 1)
(1, 2, 3, 4, 5, 8, 6, 7, 1)
(1, 2, 3, 4, 5, 8, 7, 6, 1)
(1, 2, 3, 4, 6, 5, 7, 8, 1)
(1, 2, 3, 4, 6, 5, 8, 7, 1)
(1, 2, 3, 4, 6, 7, 5, 8, 1)
#
# ... many lines omitted
#
(1, 8, 7, 6, 4, 3, 2, 5, 1)
(1, 8, 7, 6, 4, 3, 5, 2, 1)
(1, 8, 7, 6, 4, 5, 2, 3, 1)
(1, 8, 7, 6, 4, 5, 3, 2, 1)
(1, 8, 7, 6, 5, 2, 3, 4, 1)
(1, 8, 7, 6, 5, 2, 4, 3, 1)
(1, 8, 7, 6, 5, 3, 2, 4, 1)
(1, 8, 7, 6, 5, 3, 4, 2, 1)
(1, 8, 7, 6, 5, 4, 2, 3, 1)
(1, 8, 7, 6, 5, 4, 3, 2, 1)
from itertools import permutations
for a in permutations(range(2, 9)):
a = (1,) + a + (1,)
print(a)
要了解更多信息,請嘗試: how-to-generate-all-permutations-of-a-list-in-python
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.