I\'m searching for a way to count unique digits efficiently with a one liner.
For example: given the integer 623562
, return value would be 4
Here's a way that avoids creating a set each time. All but the last line are initialisation code so only happen once:
>>> from operator import or_
>>> from collections import Counter
>>> from functools import reduce
>>> bits = {str(i):2**i for i in range(10)}
>>> counts = [Counter(format(i,'b'))['1'] for i in range(2**10)]
>>> counts[reduce(or_, (bits[c] for c in str(623562)))]
4
However, it is about 3 times slower than the simple, clear, obvious len(set(str(i)))
. As usual in Python making things more complicated or trying to be excessively clever will come back and bite you on performance.