(Python)我想从150个数字的排序列表中生成长度为9的所有可能组合。但是,这不是很有效,因此我想让每个选定数字之间的差值等于或小于150,以便仅生成组合,以便以后使用。如何在Python中实现?输入列表已排序,我也需要对输出进行排序。
我已经从itertools中尝试了组合功能,但是正如我已经提到的那样,这种方法效率不高,可能会产生十亿种以上的组合。
itertools.combinations(list, 9)
Run Code Online (Sandbox Code Playgroud)
提前致谢#
我已经找到了这个解决方案,非常好。但是输出没有排序,这是我的问题。导入itertools随机导入
def combs(nums):
result = set()
for lower in nums:
options = [n for n in nums if lower <= n <= lower + 150]
result.update(itertools.combinations(options, 9))
return result
print(combs([random.randrange(0, 5000) for _ in range(150)]))
Run Code Online (Sandbox Code Playgroud)