definition
factorize: Map each unique object into a unique integer. Typically, the range of integers mapped to is from zero to the n - 1 where n is
@AChampion's
use of setdefault
got me wondering whether defaultdict
could be used for this problem. So cribbing freely from AC's answer:
In [189]: tups = [(1, 2), ('a', 'b'), (3, 4), ('c', 5), (6, 'd'), ('a', 'b'), (3, 4)]
In [190]: import collections
In [191]: import itertools
In [192]: cnt = itertools.count()
In [193]: dd = collections.defaultdict(lambda : next(cnt))
In [194]: [dd[t] for t in tups]
Out[194]: [0, 1, 2, 3, 4, 1, 2]
Timings in other SO questions show that defaultdict
is somewhat slower than the direct use of setdefault
. Still the brevity of this approach is attractive.
In [196]: dd
Out[196]:
defaultdict(>,
{(1, 2): 0, (3, 4): 2, ('a', 'b'): 1, (6, 'd'): 4, ('c', 5): 3})