首页 > 解决方案 > 来自 N 个位置的 K 个设计的场景 - Python

问题描述

我正在尝试生成所有可能的场景,我可以k在多个位置放置多个设计n。这应该给出 k^n 个场景。例如,让我们说k = 2n = 3,所有场景都是:

n1 n2 n3
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

所以必须有 8 (2^8) 个场景。

我已经尝试过,combinations但似乎都没有给出我正在尝试的解决方案。permutationscombinations_with_replacementitertools

python生成这个的函数吗?

标签: python-3.xcombinationscombinatorics

解决方案


您正在寻找产品:

for p in itertools.product(range(1,3),repeat = 3):
    print(p)

(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)

推荐阅读