Reputation: 45
I need to find out if n
is made up of odd numbers. If a number is made up of odd numbers, I should return True
, else I should return False
.
n = 1357
should return True
because all four values are odd.
n = 1356
should return False
because 6
is an even number.
How would I go about solving this? My first steps included looping over the "stringified" number but then I felt stuck because I was unable to use modulo to check whether or not the number is even or odd.
Upvotes: 1
Views: 1633
Reputation: 177481
If the set of odd digits is subtracted from the set of str(n)
and the result is empty, then it was all odd digits:
>>> def odd(n):
... return set(str(n))-set('13579')==set()
...
>>> odd(123)
False
>>> odd(113355)
True
It's fast, too, compared to checking each digit numerically:
C:\>py -m timeit -s "odd=set('13579');n=111333555777999" "all([int(x)%2 for x in str(n)])"
50000 loops, best of 5: 4.69 usec per loop
C:\>py -m timeit -s "odd=set('13579');n=111333555777999" set(str(n))-odd==set()"
200000 loops, best of 5: 1.36 usec per loop
Upvotes: 1
Reputation: 9197
n = 1357
print(all([int(x)%2!=0 for x in str(n)]))
#True
You essentially explained a possible way already. To check if a number is even use:
number % 2
Upvotes: 0
Reputation: 1154
def isMadeofEven(num):
for number in str(num):
if (int(number) % 2 !=0):
return False
return True
Upvotes: 0