Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invalid function return

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, []):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading