-1

I have a number of elements, let say [a, b, c, d], and for each pairwise combination I have a 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 am looking for a way in Python to put these elements in successive order in a way that will minimize the sum of these scores. Each unit must occur once and only once. Notice that the succession of two elements is also of importance, i.e. 'd-a' = 0 while 'a-d' = 2.

I'll be very grateful for your answers.

Thank you

Simon

2
  • 2
    Sorry, but the task is not clear to me. Please some sample output and show us what you have tried so far!
    – Klaus D.
    May 14, 2015 at 13:07
  • If I understand well, you want to find a permutation of ['a', 'b', 'c', 'd'] which minimize the sum of the scores. And the sum of the scores of ['c', 'b', 'd', 'a'], for example, is score('c', 'b') + score('c', 'd') + score('c', 'a') + score('b', 'd') + score('b', 'a') + score('d', 'a'). Is that right ? May 14, 2015 at 13:15

1 Answer 1

0
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] for a, b in zip(p, p[1:]))))

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.