I have a function find_numbers() which returns all n-digit numbers whose sum of digits is divisible by 2.
For example, find_numbers(2) will return:
[11, 13, 15, 17, 19, 20, 22, 24, 26, 28, 31, 33, 35, 37, 39, 40, 42, 44, 46, 48, 51, 53, 55, 57, 59, 60, 62, 64, 66, 68, 71, 73, 75, 77, 79, 80, 82, 84, 86, 88, 91, 93, 95, 97, 99]
Question: How can I change find_numbers() to be recursive? (in python)
def find_numbers(n: int):
result = []
for i in range(10**(n - 1), 10**n):
if (sum_of_digits(i) % 2 == 0):
result.append(i)
return result
# helper function to sum all digits of a number
def sum_of_digits(n: int) -> int:
result = 0
for digit in str(n):
result += int(digit)
return result
I've just created this recursive version, but it doesn't work. I don't know what is wrong in the following code:
def find_numbers(n: int):
def find_numbers_helper(n: int, i: int):
if (i < 10 ** n):
if (sum_of_digits(i) % 2 == 0):
return [i].append(find_numbers_helper(n, i + 1))
return find_numbers_helper(n, i=10 **(n-1))
sum(map(int, str(n))).