Here is a code which uses a helper class and a few functions to implement your algorithm. Tell me if it works as you expect
# orderer.py
# tested with python 2.6 and 3.1
from difflib import SequenceMatcher
class Orderer(object):
"Helper class for the ordering algorithm"
def __init__(self):
self.matcher = SequenceMatcher()
def order(self, alist):
"orders the list in place"
if not alist:
return
alist[0], alist[-1] = alist[-1], alist[0] # swap first and last elements
self.rank = 1 # self.rank is the index where unordered elements start
while self.rank < len(alist): # while there are unordered elements
self.matcher.set_seq1(alist[self.rank-1]) # the last sublist found
# find the best match
index, sublist = max(enumerate(alist[self.rank:], start = self.rank), key = self.key)
alist[self.rank], alist[index] = alist[index], alist[self.rank]
self.rank += 1
def key(self, item):
"score function for the call to 'max'. The score of an item is its 'ratio'"
index, sublist = item
self.matcher.set_seq2(sublist)
return self.matcher.ratio()
def order(alist):
"Order a list of lists in place with difflib"
Orderer().order(alist)
def ordered(alist):
"Return a new list of lists ordered with difflib"
other = list(alist)
order(other)
return other
if __name__ == "__main__":
my_list = [[6,5,4],[2,3,5],[1,2,3],[3,4,5],[1,2,3,4]]
print(str(my_list))
print(str(ordered(my_list)))
"""
My output --->
[[6, 5, 4], [2, 3, 5], [1, 2, 3], [3, 4, 5], [1, 2, 3, 4]]
[[1, 2, 3, 4], [1, 2, 3], [2, 3, 5], [3, 4, 5], [6, 5, 4]]
""" Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691