gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:49:12 25 4
gpt4 key购买 nike

我有 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]

关于python - 创建值集中排序数组的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62331229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com