I’m having trouble overcoming this error. I’m doing a routine similar to the merge in mergesort. Maybe I’m instantiating something wrong. Here’s the code:
def MergeAndCountSplitInv(arr, length):
left = arr[0:length/2]
right = arr[length/2+1: length]
i = 0
j = 0
numSplitInv = 0
newArray = [0] * length
for k in range(len(arr)):
if (left[i] < right[j]):
#newArray.insert(k, left[i])
newArray.append(left[i])
i = i + 1
else: #(right[j] < left[i]
#newArray[k].insert(k, right[j])
newArray.append(right[j])
j = j + 1
numSplitInv = numSplitInv + (length/2 - i)
return ReturnValue(newArray, numSplitInv)
The error is given as:
File "InversionCount.py", line 31, in MergeAndCountSplitInv
if (left[i] < right[j]):
IndexError: list index out of range
Thank you for any help
One problem is your understanding of slice indexes. These two lines:
should be changed to:
The start index is included, and the end index is the first element not included in the slice, so to get a complete partition, you use the same index for the end of the left as for the start of the right.
But the real problem is that you increment
iandjwithout checking whether you’ve walked off the end ofleftorright, so you eventually get an index error.