[英]Most efficient way to construct all possible combinations of a quadruple for 1 to n
The idea is to create all possible combinations of [a,b,c,d][e,f,g,h] where a,b,c,d,e,f,g,h are distinct integers ranging from 1 to n. 这个想法是创建[a,b,c,d] [e,f,g,h]的所有可能组合,其中a,b,c,d,e,f,g,h是从1到0的不同整数。 。 Order doesn't matter so if I have [a,b,c,d] I don't want [c,b,d,a].
顺序无关紧要,所以如果我有[a,b,c,d]我就不要[c,b,d,a]。 Same applies for [e,f,g,h].
[e,f,g,h]同样适用。
I have the code below which works but has the drawback of being a) extremely slow and b) take an insane amount of memory (I'm currently trying n=30 and using 13+ GB of memory.) 我有下面的代码可以正常工作,但缺点是a)速度极慢,b)占用大量内存(我目前正在尝试n = 30并使用13+ GB的内存。)
def build(n):
a = []
b = []
for i in range(1,n):
for j in [x for x in range(1,n) if x!= i]:
for k in [y for y in range(1,n) if (y!= i and y !=j)]:
for l in [z for z in range(1,n) if (z!= i and z!=j and z !=k)]:
if sorted([i,j,k,l]) not in a:
a.append(sorted([i,j,k,l]))
b = a
c = [i for i in product(a,b) if list(set(i[0]).intersection(i[1])) == []]
print 'INFO: done building (total: %d sets)'%len(c)
return c
Is there a more efficient way of achieving what I want? 有没有更有效的方法来实现我想要的?
Going off the top of my head, so there might be some bad syntax in here. 烦恼了,所以这里可能有一些语法错误。 Should be enough to give you an idea how you could properly approach the problem on your own, though:
不过,应该足以让您了解如何自行解决问题:
import itertools
def quads(n, required_results=None):
arr1, arr2 = range(1,n+1), range(1,n+1)
results = set() # only admits unique combinations
for combination in itertools.product(arr1, arr2):
results.add(combination)
if required_results and required_results = len(results):
# if the second argument is passed, no need to go through the whole combination-space
break
return results
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.