Home > Mobile >  TypeError: 'int' object is not subscriptable ?smth wrong with pow()?
TypeError: 'int' object is not subscriptable ?smth wrong with pow()?

Time:11-05

I have the following code:

def nar( value ):
    leng = len(str(value))
    x = 0
    
    for i in range(len(str(value))):
        while i<leng:
            if leng == 1:
                return True
            
            x = x   pow(int(value[i]), leng)
    if x == value:
        return True
    else: return False

This is the error:

x = x   pow(int(value[i]), leng)
TypeError: 'int' object is not subscriptable

Function is supposed to take a number, for example 145 and do the following: 1^3 4^3 5^3 where the power is basically the length of this number.

CodePudding user response:

The problem with your code is that

x = x   pow(int(value[i]), leng)
# Replace above line with
x = x   pow(int(str(value)[i]), leng)

The error is occurring because value is an integer and integers are not subscriptable. Adding the str(value) allows you to access each number by index.

Also, your code is an infinite loop.

This should work according to your description.

def nar( value ):
    leng = len(str(value))
    x = 0
    
    for i in range(len(str(value))):
        x = x   pow(int(str(value)[i]), leng)

    # return x
    if x == value:
        return True
    else: return False

print(nar(145))

CodePudding user response:

The problem is value[i]. You cannot subscript an integer like a string to get its decimal digits.

In order to extract a decimal digits you have to use the modulo and integer division operators. For example, to get the "4" in "145" you do

print((value % 100) // 10)

In general, to get the i-th digit (counting from the right and starting with zero), you do

print((value % (10**(i 1))) // 10**i)

This can be put into a loop to get all the digits.

Or maybe you just wanted int(str(value)[i]) instead to get the i-th element in the string representation of the value. But all these int-to-string conversions look strange.

  • Related