Bwm*_*mat 69 python permutation combinatorics
我知道itertools,但它似乎只能生成排列而不重复.
例如,我想为2个骰子生成所有可能的骰子.所以我需要[1,2,3,4,5,6]的大小为2的所有排列,包括重复:(1,1),(1,2),(2,1)......等等
如果可能的话,我不想从头开始实现这一点
mik*_*iku 118
您正在寻找笛卡尔积.
在数学中,笛卡尔积(或产品集)是两组的直接乘积.
在你的情况下,这将是{1, 2, 3, 4, 5, 6}
x {1, 2, 3, 4, 5, 6}
.
itertools
可以帮助你:
import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3),
(2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3),
(5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
Run Code Online (Sandbox Code Playgroud)
获得随机掷骰子(以完全低效的方式):
import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 28
你不是在寻找排列 - 你想要笛卡尔积.对于这个来自itertools的产品:
from itertools import product
for roll in product([1, 2, 3, 4, 5, 6], repeat = 2):
print(roll)
Run Code Online (Sandbox Code Playgroud)
在python 2.7和3.1中有一个itertools.combinations_with_replacement
功能:
>>> list(itertools.combinations_with_replacement([1, 2, 3, 4, 5, 6], 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4),
(2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6),
(5, 5), (5, 6), (6, 6)]
Run Code Online (Sandbox Code Playgroud)