0

I'm making a function where we input a number and we check whether the sum of square of digits would equal 1 or not. If it equals one, we print true, if it does not, we show it keeps on going in an endless cycle and print False.

My code:

class Solution:
    def isHappy(self, n: int,l=[]) -> bool:
        sum = 0
        print(l)
        while(n>0):
            sum = sum + int(n%10)**2
            n = n//10
        if(sum==1):
            print('ok')
            return True
        else:
            if(l.count(sum)>0):
                return False
            else:
                l.append(sum)
                Solution.isHappy(self,sum,l)


#Cross verify
Saa = Solution()
st=Saa.isHappy(7)
st

The problem is that it always returns False, I've added the extra print('ok') line to check and it actually prints it at the correct iteration but still returns false.

st value on printing = false

When I execute program for 7 it prints

[82, 68, 100]

[82, 68, 100, 49]

[82, 68, 100, 49, 97]

[82, 68, 100, 49, 97, 130]

[82, 68, 100, 49, 97, 130, 10]

ok

After 10 it should return True but still returns False

shawnin damnen
  • 313
  • 1
  • 2
  • 10
  • Can you post the whole program ? – Arpit Maiya Apr 02 '20 at 15:32
  • 1
    The final `else` clause does not have a `return` statement, therefore the function will return `None` in that case. Perhaps you meant to _return_ the result of `Solution.isHappy()` instead of just _calling_ it? – John Gordon Apr 02 '20 at 15:34
  • For me your program is working – Alex Sveshnikov Apr 02 '20 at 15:38
  • no, it returns True, in the last line just do `print(isHappy(sum,l))` and you will see it retuns true (and remove self, why are you calling a function and passing self as a param? self is just in the declaration if your function belongs to a class, you don't have to pass it when calling the function) –  Apr 02 '20 at 15:38
  • The code as shown doesn't return ``False``, it returns ``None``. It also does not "keep on going in an endless cycle". What exactly is your observed and desired output? – MisterMiyagi Apr 02 '20 at 15:55

1 Answers1

0

This is what that happens when your program has n=10:

1> sum=0  
2>While (10>0): # its true  
3>sum=sum+int(10%10)**2 #10%10=0 so sum is still 0  
4>n=10//10 #10//10 is 1 so now n=1
5>l.count(sum) =0 and so on..
6>prints ok but passes False since you called self unnecessarily in the function 

You have to change Solution.isHappy(self,sum,l) to Solution.isHappy(sum,l).
Because yes @SembeiNorimaki is right, self is just in the declaration.If your function belongs to a class, you don't have to pass it when calling the function.
Hope this helps

Shush
  • 21
  • 6