I can't figure out what I'm doing wrong, but my solution seems to be not working.
Check that the given positive integer n contains only odd digits (1, 3, 5, 7 and 9) when it is written out. Return True if this is the case, and False otherwise. Note that this question is not asking whether the number n itself is odd or even. You therefore will have to look at every digit of the given number before you can proclaim that the number contains no odd digits.
My solution (for Python)
def only_odd_digits(n):
b = list(str(n))
onlyodd = [1,3,5,7,9]
for index, value in enumerate(b):
if value in onlyodd:
return True
else:
return False
Can someone help? Thanks
CodePudding user response:
You can also use all
to avoid the loops, and then use modulo as already suggested by alparslan mimaroğlu to avoid the lookup:
def only_odd_digits(n):
digits = map(int, str(n))
return all(dig % 2 for dig in digits)
I liked the set-based answer which got deleted now. It works when using it like this:
def only_odd_digits(n):
return set(str(n)).issubset(set("13579"))
CodePudding user response:
You already created the list of integers you want to check. You just have to check every digit if it is divisible by 2. If any of them are you can just return False. If none of them are you can return True
def only_odd_digits(n):
digits = [int(digit) for digit in str(n)]
for digit in digits:
if digit % 2 == 0:
return False
return True