Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...