Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm trying to solve a Happy number algorithm problem

Look at my code:

class Solution:

def isHappy(self, n):

    nums = str(n)

    while len(nums)!=1:

        result = 0

        for num in nums:

            result += int(num) * int(num)

        nums = str(result)

    if (nums == '1'): print("True")

    else: print("False")

on the off chance that the total number of 1 is seven in the input, it has a mistake. like ["1111111, 10111111", "11101111", "11011111"] 

these numbers must be True yet results are False. 

I know it needs to rehash one more while loop however every time I attempt to fix my code, I got more errors... 

I don't do not understand how to fix this code. could you give me a clue?

1 Answer

0 votes
by (26.4k points)

You'll have to utilize a list to save the numbers you've just experienced, on the off chance that you end up falling to be categorized as one of them once more, you'll realize you are in a cycle. 

Given this present, here's the manner by which to fix your code, however, I prescribe you to attempt prior to checking the solution:

def isHappy(self, n):

    checked = []

    nums = str(n)

    while nums != '1' and not (nums in checked):

        checked.append(nums)

        result = 0

        for num in nums:

            result += int(num) * int(num)

        nums = str(result)

    if (nums == '1'): print("True")

    else: print("False")

Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Dec 11, 2020 in Python by laddulakshana (16.4k points)

Browse Categories

...