TypeError: 'int' object is not iterable?

2020-04-20 11:23发布

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

标签: python
6条回答
家丑人穷心不美
2楼-- · 2020-04-20 12:03

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)))
查看更多
狗以群分
3楼-- · 2020-04-20 12:16

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)))
查看更多
爷的心禁止访问
4楼-- · 2020-04-20 12:22

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...

查看更多
叛逆
5楼-- · 2020-04-20 12:24

It should be, s[j] = max(s[i], min(aliens[j], fib(j-i))), isn't it?

查看更多
神经病院院长
6楼-- · 2020-04-20 12:29

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.

查看更多
乱世女痞
7楼-- · 2020-04-20 12:30

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(j-i)) is an int. What you want may be s[j]=max(s[i], min(aliens[j],fib(j-i)))

查看更多
登录 后发表回答