jennmaurice
jennmaurice

Reputation: 77

Checking if its a happy number

So my code should take the digits of a 2 digit number for example (22) and square the individual digits so to [4, 4]. Then add these so 8. Then repeat this till the sum = 1 or repeat endlessly if it never = 1. My code so far will not work.

    num = int(input("--->")) #input
    sumer = 0
    numb = [int(d) for d in str(num)] #splits the input into the digits

    while sumer != 1:
        numb = [int(d) for d in str(num)] 
        numb[-1] = numb[-1] * numb[-1]
        print(numb)
        numb[-2] = numb[-2] *numb[-2]
        print(numb)
        sumer = numb[-1] + num[-2]
        print(sumb)
        numb = sumer

But when I do this I get the error Traceback (most recent call last): line 11, in sumer = numb[-1] + num[-2] TypeError: 'int' object is not subscriptable

I work in python 3.4.1 Thank you

Upvotes: 1

Views: 462

Answers (1)

ymmx
ymmx

Reputation: 4967

sumer = numb[-1] + num[-2]

should be

sumer = numb[-1] + numb[-2]

You could never go out of the while loop though!

Upvotes: 1

Related Questions