Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Count unique digits one liner (efficiently)

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.

My current way of doing it is, given integer i, im using len(set(str(i))). Creating a set is time consuming. I'm going over alot of numbers so I need an efficient way.

Also, if someone can find a way to go over all the numbers with x digits without using range() (and in a one liner..), I'll be glad. Memory limits me when using range because a list is created (I assume).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sets are optimized for this creation. Unless you want to roll out your own decimal-to-string conversion (and that would take more than one line), it's the way to go.

range only allocates memory in Python 2.x. For small numbers like 623562, the memory shouldn't be a problem. For larger numbers, use xrange in Python 2.x or simply switch to Python 3.x, where range generates the numbers just in time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...