Python反转计数器:切片索引错误

时间:2013-08-09 06:06:47

标签: python list compiler-errors slice

我正在尝试编写一个反转计数器,它将整数列表作为输入并输出反转次数。由于它将处理大型列表,我使用了分而治之的递归方法,但我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\Jonathan\Desktop\py.py", line 34, in <module>
    Inversions([1,2,3,4,5], 5)
  File "C:\Users\Jonathan\Desktop\py.py", line 13, in Inversions
    x = Inversions(numbers[:length/2 - 0.5], length/2-0.5)
TypeError: slice indices must be integers or None or have an __index__ method

这是我的代码:

def Inversions(numbers, length):
    if length == 0:
        return 0
    else:
        if length%2 == 0:
            x = Inversions(numbers[:length/2], length/2)
            y = Inversions(numbers[length/2:], length/2)
            b = sorted(numbers[:length/2], length/2)
            c = sorted(numbers[length/2:], length/2)
            z = Split(b, c)
            return x+y+z
        elif length%2 == 1:
            x = Inversions(numbers[:length/2 - 0.5], length/2-0.5)
            y = Inversions(numbers[length/2 - 0.5:], length/2-0.5)
            b = sorted(numbers[:length/2 - 0.5], length/2-0.5)
            c = sorted(numbers[length/2 - 0.5:], length/2-0.5)
            z = Split(b, c)
            return x+y+z
def Split(first, second):
    i = 1
    j = 1
    d = []
    inversions = 0
    for k in range(1,len(b)+1):
        if b[i] < C[j]:
            d[k] = b[i]
            i += 1
        else:
            d[k] = c[j]
            inversions += len(b[i:])
            j += 1
    return inversions

Inversions([1,2,3,4,5], 5)

1 个答案:

答案 0 :(得分:0)

length是偶数,这会导致非整数浮点数。改为使用整数除法。

x = Inversions(numbers[:length // 2], length // 2)