-3

I'm using an algorithm similar to Merge Sort. Firstly, I'm sorting both the lists. Then, I'm comparing the first element of each sorted list, and adding the smaller element to another list. Here's my code:

leftList=[int (x) for x in input().split()]
rightList=[int (x) for x in input().split()]
output=[]

# print(leftList,rightList)

leftList.sort()
rightList.sort()

# print(leftList,rightList)

i=j=k=0

#     Until we reach the end of either leftList or rightList, pick the smaller of
#     leftList[i] and rightList[j], and place it in the correct position in output[]

while i<len(leftList) and j<len(rightList):
    if leftList[i]<=rightList[j]:
        output[k]=leftList[i]
        i+=1

    else:
        output[k]=rightList[j]
        j+=1

    k+=1

#     When we run out of elements in either leftList or rightList,
#     place the remaining elements in output[]

while i<len(leftList):
    output[k]=leftList[i]
    i+=1
    k+=1

while j<len(rightList):
    output[k]=rightList[j]
    j+=1
    k+=1

print(output)

Here's the error that I'm getting:

 ---> 23         output[k]=rightList[j]
 IndexError: list assignment index out of range

Please help!

2 Answers2

0

In python, you can't set a list value you haven't initialised as you can in other languages. This means that, if I do something like mylist[3] = 4, the length of mylist must be at least 4 before the assignment, and the assignment can't make some slots magically appear.

So, instead of incrementing a k counter, just replace all occurences of output[k] = ... with output.append(...).

jthulhu
  • 7,223
  • 2
  • 16
  • 33
0

Your problem is at this line:

output[k]=rightList[j]

Your list is empty and cannot access the first element. The best way to insert would be the append method:

output.append(rightList[j])
vladc
  • 150
  • 1
  • 9