ElMassas
ElMassas

Reputation: 407

String object should be subscriptable but says int not subscriptable

I keep getting this error, but I can't understand what I'm doing wrong. I've looked at other similar questions and tried to apply them, but it didn't work.

The code is to chekc if the individual digits in a number, when ^3 equal to that original number.

def addCubes(a):
    total = 0
    for i in (0, len(str(a))):
        total += (a[i])**3
    if total == a:
        print("feck yah")
    else:
        print("NEIN!!!")

Upvotes: 2

Views: 3558

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

You can solve this in just one-line! Simply use a generator expression inside sum where you cube the integer value of each character in the stringified a:

sum(int(d)**3 for d in str(a)) == a

I will let you incorporate this into your if-else statements, but you can see it works:

When...

a = 28 --> False
a = 153 --> True

Upvotes: 1

neehari
neehari

Reputation: 2612

Convert a to string, then access the digit at index i of the string, convert the digit to int, then cube it:

total = 0
for i in range(0, len(str(a))):
    total += int(str(a)[i])**3

You could also try this:

for i in str(a):
        total += int(i) ** 3

Rewriting the function:

def addCubes(a):
    total = 0
    for i in str(a):
        total += int(i) ** 3
    if total == a:
        print("feck yah")
    else:
        print("NEIN!!!")

addCubes(371)

feck yah
>>>

Upvotes: 3

Related Questions