Count unique digits one liner (efficiently)

前端 未结 3 1202
春和景丽
春和景丽 2020-12-12 05:51

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

3条回答
  •  -上瘾入骨i
    2020-12-12 06:14

    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.

提交回复
热议问题