Skip to content

Commit 1e85ac8

Browse files
Merge pull request #642 from subahanii/patch-1
update happy_num
2 parents 27599f4 + d242e81 commit 1e85ac8

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

happy_num

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#Way2 1:
2+
13
#isHappyNumber() will determine whether a number is happy or not
24
def isHappyNumber(num):
35
rem = sum = 0;
@@ -17,7 +19,27 @@ while(result != 1 and result != 4):
1719

1820
#Happy number always ends with 1
1921
if(result == 1):
20-
print(str(num) + " is a happy number");
22+
print(str(num) + " is a happy number after apply way 1");
2123
#Unhappy number ends in a cycle of repeating numbers which contain 4
2224
elif(result == 4):
23-
print(str(num) + " is not a happy number");
25+
print(str(num) + " is not a happy number after apply way 1");
26+
27+
28+
29+
30+
31+
#way 2:
32+
33+
#Another way to do this and code is also less
34+
n=num
35+
setData=set() #set datastructure for checking a number is repeated or not.
36+
while 1:
37+
if n==1:
38+
print("{} is a happy number after apply way 2".format(num))
39+
break
40+
if n in setData:
41+
print("{} is Not a happy number after apply way 2".format(num))
42+
break
43+
else:
44+
setData.add(n) #adding into set if not inside set
45+
n=int(''.join(str(sum([int(i)**2 for i in str(n)])))) #Pythonic way

0 commit comments

Comments
 (0)