如何将0,1,-1位排列在6个位置(python)?
How to arrange 0,1,-1 digits at 6 positions (python)?
我想在 6 个位置放置三个数字 [0,1,-1]。它应该给出 3^6 = 729 种组合。代码应该 return 类似于:
(0,0,0,0,0,0)
(0,0,0,0,0,1)
(0,0,0,0,0,-1)
(0,0,0,0,1,1)
(0,0,0,0,1,-1)
.
.
(-1,-1,-1,-1,-1,0)
(-1,-1,-1,-1,-1,-1)
我尝试使用“itertools.permutations”,但对如何将 0,1,-1 合并到其中感到困惑。
使用itertools.product
import iertools
assert(sum(1 for _ in itertools.product([-1, 0, 1], repeat=6)) == 3**6)
如果你知道itertools.permutations
我认为不需要更多解释。
查看 itertools.product(*iterables, repeat=1)
here。
像这样使用:
> product([-1, 0, 1], repeat=6)
[...]
(1, 1, 1, 0, -1, -1),
(1, 1, 1, 0, -1, 0),
(1, 1, 1, 0, -1, 1),
(1, 1, 1, 0, 0, -1),
(1, 1, 1, 0, 0, 0),
(1, 1, 1, 0, 0, 1),
(1, 1, 1, 0, 1, -1),
(1, 1, 1, 0, 1, 0),
(1, 1, 1, 0, 1, 1),
(1, 1, 1, 1, -1, -1),
(1, 1, 1, 1, -1, 0),
(1, 1, 1, 1, -1, 1),
(1, 1, 1, 1, 0, -1),
(1, 1, 1, 1, 0, 0),
(1, 1, 1, 1, 0, 1),
(1, 1, 1, 1, 1, -1),
(1, 1, 1, 1, 1, 0),
(1, 1, 1, 1, 1, 1)]
得到你len(list(product([-1, 0, 1], repeat=6))) = 729
我想在 6 个位置放置三个数字 [0,1,-1]。它应该给出 3^6 = 729 种组合。代码应该 return 类似于:
(0,0,0,0,0,0)
(0,0,0,0,0,1)
(0,0,0,0,0,-1)
(0,0,0,0,1,1)
(0,0,0,0,1,-1)
.
.
(-1,-1,-1,-1,-1,0)
(-1,-1,-1,-1,-1,-1)
我尝试使用“itertools.permutations”,但对如何将 0,1,-1 合并到其中感到困惑。
使用itertools.product
import iertools
assert(sum(1 for _ in itertools.product([-1, 0, 1], repeat=6)) == 3**6)
如果你知道itertools.permutations
我认为不需要更多解释。
查看 itertools.product(*iterables, repeat=1)
here。
像这样使用:
> product([-1, 0, 1], repeat=6)
[...]
(1, 1, 1, 0, -1, -1),
(1, 1, 1, 0, -1, 0),
(1, 1, 1, 0, -1, 1),
(1, 1, 1, 0, 0, -1),
(1, 1, 1, 0, 0, 0),
(1, 1, 1, 0, 0, 1),
(1, 1, 1, 0, 1, -1),
(1, 1, 1, 0, 1, 0),
(1, 1, 1, 0, 1, 1),
(1, 1, 1, 1, -1, -1),
(1, 1, 1, 1, -1, 0),
(1, 1, 1, 1, -1, 1),
(1, 1, 1, 1, 0, -1),
(1, 1, 1, 1, 0, 0),
(1, 1, 1, 1, 0, 1),
(1, 1, 1, 1, 1, -1),
(1, 1, 1, 1, 1, 0),
(1, 1, 1, 1, 1, 1)]
得到你len(list(product([-1, 0, 1], repeat=6))) = 729