'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?
Solution 1:[1]
You could convert your number to a string, then to a set to get the unique digits.
You just have to iterate over digits in 0-9 to find the ones not present in your original number :
>>> set(map(int,str(4059304593)))
set([0, 9, 3, 4, 5])
>>> digits = _
>>> [i for i in range(10) if i not in digits]
[1, 2, 6, 7, 8]
Solution 2:[2]
L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
j = 0
nL = [0, 0, 0, 0, 0, 0, 0, 0, 0]
n = 1004 #number
while n:
i = n%10
nL[i] = 1
n //= 10
OUT
nL = [1, 1, 0, 0, 1, 0, 0, 0, 0, 0]
Explanation:
if nL[i] is 1, then the i-th digit is in n
Solution 3:[3]
Since you just want to find out which digits aren't in your number:
def not_in_number(n):
return {*range(10)} - {*map(int, {*str(n)})}
Usage:
>>> not_in_number(4059304593)
{1, 2, 6, 7, 8}
This takes the set of digits ({*range(10)}) and substracts from it the set of digits of your number ({*map(int, {*str(n)})}), created by mapping the set of digit characters to integers. If you find the {*...} notation confusing, you can always use set(...) instead, which will also work for Python 2.7+:
def not_in_number(n):
return set(range(10)) - set(map(int, set(str(n))))
Solution 4:[4]
Another way is using - with sets:
set('0123456789') - set(str(4059304593))
Result are all digits that aren't in your integer:
{'2', '7', '1', '6', '8'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Duminil |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Miguel |
