TypeError: 'int' object does not support element assignment

Why am I getting this error?

a[k] = q % b TypeError: 'int' object does not support item assignment 

the code:

 def algorithmone(n,b,a): assert(b > 1) q = n k = 0 while q != 0: a[k] = q % b q = q / b ++k return k print (algorithmone(5,233,676)) print (algorithmone(11,233,676)) print (algorithmone(3,1001,94)) print (algorithmone(111,1201,121)) 
+8
python typeerror
source share
1 answer

You pass an integer to your function as a . Then you try to assign it as: a[k] = ... , but this does not work, since a is a scalar ...

This is the same thing you tried:

 50[42] = 7 

This statement does not make much sense, and the python will yell at you the same way (presumably).

Also, ++k does not do what you think it does - it is parsed as (+(+(k))) - that is, the byte code is simply UNARY_POSITIVE twice. What you really want is something like k += 1

Finally, be careful with statements such as:

 q = q / b 

The brackets that you use with printing mean that you want to use this in python3.x at some point. but x/y behaves differently on python3.x than on python2.x. Looking at the algorithm, I assume that you want integer division (since you check q != 0 , which is hard to satisfy with float). In this case, you should consider using:

 q = q // b 

which performs integer division on both python2.x and python3.x.

+14
source share

All Articles