Vin*_*ent 2 python combinatorics
我有 p 严格升序值,x0 < x1 < ... < xp
我想生成所有可能的大小为 n 的数组,其中填充了上述值 a[0] <= a[1] <= ... <= a[n-2] <= a[n-1]。例如:
[x0, x0, x0, ... , x0]
[x0, x1, x1, ... , x1]
[x0, x0, x1, ... , x1]
[x1, x2, x3, ... , x3]
etc...
这样做的最优雅和最有效的方法是什么?
出乎意料的简单;-)
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]