创建一组值集中的排序数组的所有组合

问题描述 投票:2回答:1

我有p个严格的升序值,x0

我想生成大小为n的所有可能的数组,并用上述值填充,其中a [0] <= a [1] <= ... <= a [n-1] <= a [n]。例如:

[x0, x0, x0, ... , x0]
[x0, x1, x1, ... , x1]
[x0, x0, x1, ... , x1]
[x1, x2, x3, ... , x3]

etc...

最优雅,最有效的方法是什么?

python combinatorics
1个回答
3
投票

令人惊讶的简单;-)

def crunch(xs, n):
    from itertools import combinations_with_replacement as cwr
    for t in cwr(xs, n):
        yield list(t)

然后,例如

for x in crunch([1, 5, 7, 8, 10], 3):
    print(x)

显示

[1, 1, 1]
[1, 1, 5]
[1, 1, 7]
[1, 1, 8]
[1, 1, 10]
[1, 5, 5]
[1, 5, 7]
[1, 5, 8]
[1, 5, 10]
[1, 7, 7]
[1, 7, 8]
[1, 7, 10]
[1, 8, 8]
[1, 8, 10]
[1, 10, 10]
[5, 5, 5]
[5, 5, 7]
[5, 5, 8]
[5, 5, 10]
[5, 7, 7]
[5, 7, 8]
[5, 7, 10]
[5, 8, 8]
[5, 8, 10]
[5, 10, 10]
[7, 7, 7]
[7, 7, 8]
[7, 7, 10]
[7, 8, 8]
[7, 8, 10]
[7, 10, 10]
[8, 8, 8]
[8, 8, 10]
[8, 10, 10]
[10, 10, 10]
© www.soinside.com 2019 - 2024. All rights reserved.