简体   繁体   中英

TypeError: 'int' object is not iterable?

I was implementing the dynamic programming algorithm and I got this error. This is my code:

def shoot(aliens):
    s=[0]*10
    s[0]=0
    s[1]=0
    for j in xrange(2,len(aliens)):
        for i in xrange(0,j):
           s[j]=max(s[i] + min(aliens[j],fib(j-i))) <---Error here
    print s[len(aliens)-1]
    return s[len(aliens)-1]

def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)

aliens=[1,10,10,1]
print shoot(aliens)

it says that:

Traceback (most recent call last):
File "module1.py", line 30, in <module>
print shoot(aliens)
File "module1.py", line 19, in shoot
s[j]=max(s[i] + min(aliens[j],fib(j-i)))
TypeError: 'int' object is not iterable

Please help me

UPDATE: oh, I get it. I mean

s[j]=max(s[i] + min(aliens[j],fib(j-i)))

But im wrong. so, I edited it like that, but I do not know how to use max() to take out the largest in an array.

    b=0
    for j in xrange(2,len(aliens)):
        for i in xrange(0,j):
           a[b]=(s[i] + min(aliens[j],fib(j-i)))
           b+=1
        s[j]=Largest(a[b]);   <--How can I do that with Max() function

max and min functions require several arguments or a range of elements. Your call to min() has two arguments (ok), but your call to max() has only one. Not sure what you want to maximize here...

You are doing something like following:

>>> max(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

Did you want to do this?

s[j] = max(s[i], min(aliens[j],fib(j-i)))

or

s[j] = max(s[j], s[i] + min(aliens[j],fib(j-i)))

max needs an iterable argument.

max(...)
max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

But what you passed to it by s[i] + min(aliens[j],fib(ji)) is an int . What you want may be s[j]=max(s[i], min(aliens[j],fib(ji)))

It means you cannot iterate over a single int object.

max() and min() want either a number of values of whose they return the largest resp. the smallest, or they want an objkect which can be iterated over.

Your max() call is executed with one single argument which, then, should be iterable, but isn't.

应该是, s[j] = max(s[i], min(aliens[j], fib(ji))) ,不是吗?

http://docs.python.org/2/library/functions.html#max

max(iterable[, key])
max(arg1, arg2, *args[, key])

didn't you mean:

s[j] = max(s[i], min(aliens[j],fib(j-i)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM