我想订购数百个2-15元组的子集。想象一个元组就像一块多米诺骨牌。两个数字固有地合为一体。没有定义哪个是第一个,哪个是第二个数字。这样就可以翻转了。
查找链中最多碎片(多元组)的多米诺骨牌(元组)的顺序。形成链的条件就像在多米诺骨牌中一样:第n个元组的第二个值==第n + 1个元组的第一个值。
其他注释:元组不一定形成循环
通过检查每个组合得到的技巧,强行强加它。一个由6个元组组成的链已经具有45360个可能性(带有翻转)
#brute forcing it by trying every possibility
#one subset
MN=[(3,4), (4,5), (8,5), (17,3), (34,56), (4,34)]
n=len[MN]
#initializing some variables for counting, etc.
count=0 #count the possibilities
score_max=0
best_sequence=None
from itertools import permutations
#helper functions
def calculate_optimization_score(MN):
n=len(MN)
score=0
for i in range(n-1):
if MN[i][1]==MN[i+1][0]:
score=score+1
return score
def flip_MN(MN, bool_ls):
MN_new=list(MN) #to be safe, make a copy
for i,e in enumerate(MN_new):
if bool_ls[i]==True:
MN_new[i]=tuple(reversed(MN_new[i]))
return MN_new
for nb_flip_MN in range(n):
# make True False array with nb_flip_MN True-values
bool_ls=[]
for i in range(nb_flip_MN):
bool_ls.append(True)
for i in range(n-nb_flip_MN):
bool_ls.append(False)
perm = set(list(permutations(bool_ls))) # and all permutations of that
for i,e in enumerate(perm):
#make the sequence with the flipped MN according to perm
MN_with_flip=flip_MN(MN, e)
for j,sequence in enumerate(list(permutations(MN_with_flip))):
score=calculate_optimization_score(sequence)
count=count+1
if score>score_max:
score_max=score
best_sequence=sequence