Why do I get this error?
a[k] = q % b
TypeError: 'int' object does not support item assignment
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))
You’re passing an integer to your function as
a. You then try to assign to it as:a[k] = ...but that doesn’t work sinceais a scalar…It’s the same thing as if you had tried:
That statement doesn’t make much sense and python would yell at you the same way (presumably).
Also,
++kisn’t doing what you think it does — it’s parsed as(+(+(k)))— i.e. the bytcode is justUNARY_POSITIVEtwice. What you actually want is something likek += 1Finally, be careful with statements like:
The parenthesis you use with print imply that you want to use this on python3.x at some point. but,
x/ybehaves differently on python3.x than it does on python2.x. Looking at the algorithm, I’m guessing you want integer division (since you checkq != 0which would be hard to satisfy with floats). If that’s the case, you should consider using:which performs integer division on both python2.x and python3.x.