Test cases:
group_ordered([1,3,2,3,6,3,1]) = [1,1,3,3,3,2,6]
group_ordered([1,2,3,4,5,6,1]) = [1,1,2,3,4,5,6]
I have some code already, but it's ugly and probably slow on large lists as well, since for each unique item I'm looking at the whole list. I came up with this algorithm, but I am wondering if there is a faster, cleaner, or more pythonic way I can do this:
def make_order_list(list_in):
order_list = []
for item in list_in:
if item not in order_list:
order_list.append(item)
return order_list
def group_ordered(list_in):
if list_in is None:
return None
order_list = make_order_list(list_in)
current = 0
for item in order_list:
search = current + 1
while True:
try:
if list_in[search] != item:
search += 1
else:
current += 1
list_in[current], list_in[search] = list_in[search], list_in[current]
search += 1
except IndexError:
break
return list_in