# # Utility functions. # import itertools def unique(it): """Remove all duplicates from an iterable, leaving only the first instance of each duplicate. This is different from turning into a set because it preserves the order of the items.""" it = iter(it) # This will raise StopIteration if the iterator is empty, # which is OK. head = it.next() # Now remove all items equal to the head. # This runs in quadratic time (and linear stack space), # but never mind. yield head for i in itertools.ifilter(lambda i: i != head, unique(it)): yield i