【问题标题】:Python gives "int is not iterable" error even though the code looks clean即使代码看起来很干净,Python 也会给出“int is not iterable”错误
【发布时间】:2014-12-10 00:42:40
【问题描述】:

我基本上是在尝试编写计数反转的算法(使用合并排序的分治策略)。我首先尝试在一个小数组中对其进行测试,但出现以下错误:

Traceback (most recent call last):
  File "cntinv.py", line 26, in <module>
    ans = count_inversions(array)[1]
  File "cntinv.py", line 19, in count_inversions
    a, left = count_inversions(array[:mid])
  File "cntinv.py", line 19, in count_inversions
    a, left = count_inversions(array[:mid])
TypeError: 'int' object is not iterable

这是我的代码:

def count_split_inversions(a, b):
    c, cnt = [], 0
    while len(a) > 0 and len(b) > 0:
        if b[0] < a[0]:
            c.append(b.pop(0))
            cnt += len(a)
        else:
            c.append(a.pop(0))
    if len(a) > 0:
        c.extend(a)
    else:
        c.extend(b)
    return(c, cnt)

def count_inversions(array):
    n = len(array)

    if n <= 1: return(0)

    mid = n // 2
    a, left = count_inversions(array[:mid])
    b, right = count_inversions(array[mid:])
    c, split = count_split_inversions(a, b)

    return(c, left + right + split)

array = [1, 3, 5, 2, 4, 6]
ans = count_inversions(array)[1]
print("The answer is:", str(ans))

在错误消息的帮助下我找不到错误。因此,如果您能帮我指出我的错误,我将不胜感激。

提前致谢。 :)

【问题讨论】:

  • 就是这样。发现错误! :) 谢谢。我不敢相信我没有看到。 :3

标签: python typeerror


【解决方案1】:

如果n &lt;= 0count_inversions() 返回0,而不是一个元组:

def count_inversions(array):
    ...
    if n <= 1: return(0)
    ...

由于调用函数需要一个元组,这会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2022-11-14
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多