I'm trying to write an inversions counter that takes a list of integers as input and outputs the number of inversions. Since it's going to handle large lists, I'm using a divide and conquer recursive approach, but I'm getting the following error:
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
Here is my code:
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)