This is my code, why when i print(is_happy(13)) i got True, but in the result of happy_numbers i don’t get 13 and many correct numbers?
def is_happy(n, result = []):
next_number = sum(map(lambda x: int(x) ** 2, str(n)))
if next_number == 1:
return True
elif next_number in result:
return False
else:
result.append(next_number)
return is_happy(next_number)
def happy_numbers(n):
result = []
for i in range(1, n + 1):
if is_happy(i):
result.append(i)
return result
>Solution :
The issue is that you are using a mutable default argument in is_happy(n, result=[]). This means that the result won’t start as an empty list every time it’s run but rather will keep its old results.
To counter this, I’d remove the default argument and explicitly pass the array:
def is_happy(n, result):
# all the stuff you already had
return is_happy(next_number, result)
and in the other function
if is_happy(i, []):