Question 7 from Lab 3 of Berkeley's CS61A course says:
The following examples of recursive functions show some examples of common recursion mistakes. Fix them so that they work as intended. [...]
def even_digits(n): """Return the percentage of digits in n that are even. >>> even_digits(23479837) # 3 / 8 0.375 """ if n == 0: return num_digits / num_evens num_digits, num_evens = 0, 0 if n % 2 == 0: counter += 1 num_evens += 1 return (even_digits(n // 10) + num_evens) / counter
As per the assignment, below code is suppose to solve this problem, recursively (MUST not be non-recursive).
def even_digits(n, count_even = 0, count = 0):
"""Return the percentage of digits in n that are even.
>>> even_digits(23479837) # 3 / 8
0.375
"""
if n == 0:
return count_even / count
if (n % 2) == 0:
return even_digits(n // 10, count_even + 1, count + 1)
else:
return even_digits(n // 10, count_even, count + 1)
Is this code readable? Can we improve this solution?