Home > Enterprise >  Happy Number from Python list
Happy Number from Python list

Time:07-01

i am an absolute Beginner in Python and im trying to, find happy numbers from a given List. but it doesn't give anything back, i searched for a solution but i couldnt find one. My code is this :

a = [1,4,7,82]
def is_happy(a):
    for i in range (len(a)):
        sum = a[i]
        for digit in str(a[i]):
             sum = 0
        while sum != 1 and sum !=4:      
                sum = sum   int(digit) ** 2
        if sum ==1:
                b.append(a[i])
        return b
print(is_happy(a))

May you can help me. Thank you!

CodePudding user response:

Converting the integers to strings in order to calculate the sum of squares is not a great idea - better to combine division and modulus. Write a discrete function to do that.

Then write a function that handles one value at a time. Call that multiple times - once for each item in your list.

Here's an approach you could use:

def ss(n):
    r = 0
    while n > 0:
        d = n % 10
        r  = d * d
        n //= 10
    return r

def is_happy(n):
    if n > 0:
        while True:
            if (n := ss(n)) == 1:
                return True
            if n == 4:
                break
    return False

a = [1, 4, 7, 82]

for n in a:
    print(n, is_happy(n))

Output:

1 True
4 False
7 True
82 True

CodePudding user response:

Eminos, I will help with some suggestions.
In Python, white space is very important, and it takes some time for any newbie to get used to.

In for i in range (len(a)):, there is an extra space between "range" and "(". It could still run, but is not the preferred style, since it is defined as a range() function.

Code blocks need consistent spacing (left indent). Each level should be 2 or 4 spaces, with 4 spaces recommended by PEP8 (not tabs). The below examples have too many spaces in left indent. sum = 0 sum = sum int(digit) ** 2 b.append(a[i])

To calculate the squre of a number, it is not necessary to change data type from integer to string.
squared = a[i]**2

To keep track of your squared numbers list, try:

    tally = 0
    for i in range(len(a)):
       squared = a[i]**2  # squares each number in list
       tally  = squared  # keeps a running sum of squared numbers

Generally, I think a function like is_happy should return a true/false statement(s). So a sample returned list can be ["True", "False", "True", "True"]

More work to do, but hope that will get you started. :-)

  • Related