File tree Expand file tree Collapse file tree 3 files changed +38
-0
lines changed Expand file tree Collapse file tree 3 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -17,6 +17,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
17
17
- [ 125 Valid Palindrome] ( https://leetcode.com/problems/valid-palindrome/description/ )
18
18
- [ 169 Majority Element] ( https://leetcode.com/problems/majority-element/description/ )
19
19
- [ 189 Rotate Array] ( https://leetcode.com/problems/rotate-array/description/ )
20
+ - [ 202 Happy Number] ( https://leetcode.com/problems/happy-number/description/ )
20
21
- [ 205 Isomorphic Strings] ( https://leetcode.com/problems/isomorphic-strings/description/ )
21
22
- [ 242 Valid Anagram] ( https://leetcode.com/problems/valid-anagram/description/ )
22
23
- [ 290 Word Pattern] ( https://leetcode.com/problems/word-pattern/description/ )
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def sum_of_squares (self , n : int ) -> int :
3
+ return sum (int (digit ) ** 2 for digit in str (abs (n )))
4
+
5
+ def isHappy (self , n : int ) -> bool :
6
+ """
7
+ Write an algorithm to determine if a number n is happy.
8
+
9
+ A happy number is a number defined by the following process:
10
+ - Starting with any positive integer, replace the number by the sum of the squares of its digits.
11
+ - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
12
+ - Those numbers for which this process ends in 1 are happy.
13
+
14
+ Return true if n is a happy number, and false if not.
15
+ """
16
+ values = {}
17
+ while n != 1 :
18
+ if n in values :
19
+ return False
20
+ values [n ] = True
21
+ n = self .sum_of_squares (n )
22
+ return True
Original file line number Diff line number Diff line change
1
+ import pytest
2
+
3
+ from awesome_python_leetcode ._202_happy_number import Solution
4
+
5
+
6
+ @pytest .mark .parametrize (
7
+ argnames = ["n" , "expected" ],
8
+ argvalues = [
9
+ (19 , True ),
10
+ (2 , False ),
11
+ ],
12
+ )
13
+ def test_func (n : int , expected : bool ):
14
+ is_happy = Solution ().isHappy (n )
15
+ assert is_happy == expected
You can’t perform that action at this time.
0 commit comments