python - How to generate an optimal order of multiple elements based on pairwise element score values -


i have number of elements, let [a, b, c, d], , each pairwise combination have score:

[['d-a', 0], ['a-b', 0], ['b-a', 0],  ['a-c', 2], ['c-a', 0], ['a-d', 2],  ['d-b', 1], ['b-c', 2], ['c-b', 0],  ['b-d', 2], ['d-c', 2], ['c-d', 2]] 

i looking way in python put these elements in successive order in way minimize sum of these scores. each unit must occur once , once. notice succession of 2 elements of importance, i.e. 'd-a' = 0 while 'a-d' = 2.

i'll grateful answers.

thank you

simon

elements = ['a', 'b', 'c', 'd'] scores = [['d-a', 0], ['a-b', 0], ['b-a', 0], ['a-c', 2], ['c-a', 0], ['a-d', 2],           ['d-b', 1], ['b-c', 2], ['c-b', 0], ['b-d', 2], ['d-c', 2], ['c-d', 2]]  s = dict(scores) print(min(itertools.permutations(elements),           key=lambda p: sum(s[a+'-'+b] a, b in zip(p, p[1:])))) 

prints ('c', 'a', 'b', 'd').


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -