Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

python - TypeError: 'int' object does not support item assignment

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 since a is a scalar...

It's the same thing as if you had tried:

50[42] = 7

That statement doesn't make much sense and python would yell at you the same way (presumably).

Also, ++k isn't doing what you think it does -- it's parsed as (+(+(k))) -- i.e. the bytcode is just UNARY_POSITIVE twice. What you actually want is something like k += 1

Finally, be careful with statements like:

q = q / b

The parenthesis you use with print imply that you want to use this on python3.x at some point. but, x/y behaves differently on python3.x than it does on python2.x. Looking at the algorithm, I'm guessing you want integer division (since you check q != 0 which would be hard to satisfy with floats). If that's the case, you should consider using:

q = q // b

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...