我正在寻找一种非常有效的方法来计算 n 个列表中的所有可能组合,然后保持组合具有最小的最小二乘差。
我已经有一个代码可以做到这一点,但是当它达到数百万个组合时,事情就会变慢。
Candidates_len包含长度为 [[500, 490, 510, 600][300, 490, 520][305, 497, 515]] 的列表的列表Candidate_name包含名称为 [['a', ' 的列表的列表b', 'c', 'd']['mi', 'mu', 'ma']['pi', 'pu', 'pa']]
两个列表都有n 个列表。
# Creating the possible combinations and store the lists of lengths in vector r
r=[[]]
for x in candidates_len:
r = [ i + [y] for y in x for i in r ]
#Storing the names of the combinations and store the lists of identifiers in vector z
z=[[]]
for x in candidates_name:
z = [ i + [y] for y in x for i in z ]
#Calculating distances and storing the minimum one
min_index = 0
min_dist = 0
list_best = []
for index, item in enumerate(r):
n = 0
dist = 0
while n < len(candidates_len):
for i in range(n,len(candidates_len)):
dist = dist + (item[n]-item[i])**2
n=n+1
if index==0:
min_dist = dist
min_index = index
list_best.append(item)
elif dist < min_dist:
min_dist = dist
min_index = index
list_best = []
list_best.append(z[index])
least_combination = min_index
一个硬案例: http: //pastebin.com/BkVQTQWK
以下是一些测试时间。不到一分钟左右会很好。我不知道这是否可能。
combinations time(s) 77760 1.255663 41184 1.580333 69120 6.214786 8960 1.131834 537600 14.855361 89100 1.264126 16384 3.247404 4199040 666.853284 226800 3.935878 9289728 679.064149