Reputation: 33
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?
def valid(n):
number = str(n)
position = number.find("0")
if "0" not in number:
return 0
return 1 + valid(number[(position+1):])
print(valid(12340006))
Upvotes: 0
Views: 2121
Reputation: 7858
We can note that
def is_valid(num):
n, r = divmod(num, 10)
if n == 0:
return r != 0
return is_valid(n) ^ (r == 0)
Upvotes: 3
Reputation: 15505
If you are converting the number to a string using str
, then you don't have to implement your own loop using recursion. You can count the number of '0'
in the string using str.count
, then test whether that number is odd or even using %
.
def is_valid(n):
s = str(n)
nb_of_zeroes = s.count('0')
return (nb_of_zeroes % 2 == 0)
If you want to implement the logic yourself, rather than using str
and count
, then you can loop on the digits of n
with divmod(n, 10)
to extract n%10
(the unit digit) and n//10
(the number without its unit digit). For instance, divmod(9836, 10)
is (983, 6)
.
def is_valid(n):
if n == 0:
return False # special case for 0 which is a bit different from other numbers
else:
nb_of_zeroes = 0
while n >= 10:
n,u = divmod(n, 10)
if u == 0:
nb_of_zeroes += 1
return (nb_of_zeroes % 2 == 0)
Upvotes: 0
Reputation: 260420
You have a number, don't convert to string but rather use divmod
and division by 10:
def valid(num, count=0):
num, r = divmod(num, 10) # extract the last digit (r)
if num == 0: # we exhausted the number
return count%2==0 # is there an even number of zeros?
else:
return valid(num, count=count+int(r==0))
def valid(num, count=None):
if count is None:
count = int(num==0)
num, r = divmod(num, 10)
if num == 0:
return count%2==0
else:
return valid(num, count=count+int(r==0))
Example:
>>> valid(12340006)
False
>>> valid(10203)
True
>>> valid(0)
False
Upvotes: 0
Reputation: 158
I believe the problem is the 0
returned from the if "0" not in number
condition. You can try this way:
def valid(n):
zeros = str(n).count("0")
if zeros == 0:
return False
else:
return zeros % 2 == 0
Which should work.
Upvotes: 0
Reputation: 1
def valid(n):
number = str(n)
position = number.find("0")
if "0" not in number:
return 0
return 1 + valid(number[(position+1):])
print("True" if valid(12340006)%2 ==0 else "False")
Upvotes: 0