
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Happy Number in Python
Here we will see how to detect a number n is one Happy number or not. So 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.
Suppose the number is 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
Example
Let us see the following implementation to get better understanding −
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ 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) ob1 = Solution() op = ob1.isHappy(19) print("Is Happy:",op)
Input
19
Output
Is Happy: True
- Related Articles
- Happy Numbers in Python
- Python program to check if the given number is Happy Number
- Program to find maximum number of people we can make happy in Python
- Happy Hormones
- The Happy Prince
- Longest Happy String in C++
- Longest Happy Prefix in C++
- Python program to print all Happy numbers between 1 and 100
- C++ program to print Happy Birthday
- Determining happy numbers using recursion JavaScript
- Write a program for Happy Woman’s Day in c++
- How can I be happy in life at all times?
- What's the best way to ensure a happy marriage?
- Java Program to check the birthday and print Happy Birthday message
- Haskell Program to Check the birthday and print Happy Birthday message

Advertisements