Rahman Fahd
Rahman Fahd

Reputation: 33

Happy Number String Python function

I am pretty new to Python and just got started in Leet and I am doing the Happy Number question, only half of the test cases have been passed. I would appreciate any help. Thanks

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

My test cases were 19, 100 where it output True correctly but when I do 7, it is wrong

    def isHappy(self, n: int) -> bool:
        if (n == 1):
            return True
        sum = 0
        flag = False
        for j in range(1,100):  
            x = str(n)
            a = list(x)
            for i in range(0,len(a)):
              sum += int(a[i])*int(a[i])
              if sum == 1:
                return True
                break
            else:
                    x = sum 
                    return False

Upvotes: 0

Views: 378

Answers (1)

alani
alani

Reputation: 13049

Here is an implementation using a set to keep track of numbers that we have already seen. (I've removed the self argument here for sake of something that can be run outside of your test class.)

def isHappy(n: int) -> bool:
    seen = set()
    while True:
        if n == 1:
            return True
        if n in seen:
            return False
        seen.add(n)
        n = sum(int(c) ** 2 for c in str(n))

Your code has various issues aside from the fact that the number 100 is arbitrary.

Mainly that you never update n in your loop. Also you do not wait for the completion of the for loop before testing sum (in fact your break is never reached), you initialise sum only once, and you return False prematurely. Here is a minimally corrected version of your code, although still subject to the fact that there is no rule about 100 maximum iterations.

def isHappy(n: int) -> bool:
    if (n == 1):
        return True
    for j in range(1,100):
        x = str(n)
        a = list(x)
        sum = 0
        for i in range(0,len(a)):
          sum += int(a[i])*int(a[i])
        if sum == 1:
            return True
        else:
            n = sum 
    return False

Upvotes: 1

Related Questions