Computer >> Computer tutorials >  >> Programming >> Python

Happy Numbers in Python


Suppose we have a number n. We shall check whether it is one Happy number or not. As we know, the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be happy number.

So, the input is like 19, the output will be true as the number is happy number. As we can see from 19, we will get

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

To solve this, we will follow these steps −

  • Here we will use the dynamic programming approach, and solve this using recursion
  • Base case is, when n = 1, then return true
  • When n is already visited, return false
  • mark n as visited
  • n := n as string, l := list of all digits in n
  • temp := squared sum of all digits
  • return function recursively with parameter temp and visited list

Let us see the following implementation to get better understanding −

Example

class Solution(object):
   def isHappy(self, n):
      return self.solve(n,{})
   def solve(self,n,visited):
      if n == 1:
         return True
      if n in visited:
         return False
         visited[n]= 1
         n = str(n)
         l = list(n)
         l = list(map(int,l))
         temp = 0
         for i in l:
            temp += (i**2)
         return self.solve(temp,visited)
ob = Solution()
print(ob.isHappy(19))

Input

19

Output

True