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
208 views
in Technique[技术] by (71.8m points)

python - How to check if a specific digit is in an integer

I want to check if, for example, the digit '2' is in 4059304593. My aim is to then check if there are any of the digits 1-9 not in my integer. This is what I have tried:

    for i in xrange(10):
    for j in xrange(100):
        num = str(i^j)
        one_count = 0
        two_count = 0
        for k in xrange(len(num)):
            if num[k] == 1:
                one_count += 1
            if num[k] == 2:
                two_count += 1                    

Then my "counts" would go all the way down to nine_count, and if any of the counts are 0, then that digit isn't in 'num'. From what I've read on these sites, my script would be inefficient - can someone point out a better way?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This "digit" thing calls for a string approach, not a numeric one (reminds me of some Project Euler puzzles).

I'd create a set out of the digits of your number first (removing duplicates at the same time)

s = set(str(4059304593))

then to check for a digit:

print('2' in s)

(note that in for a set is performant)

then, to check whether s contains all the 013456789 digits:

print(s.issuperset("013456789"))

(if this must be done multiple times, it may be worth to create a set with the string, issuperset will work faster)


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

...