Fredrikj31
Fredrikj31

Reputation: 155

Python list index out of range - Algorithm

I have this error where I can loop through an array, and I don't know the correct thing to do. But I have tried to insert 0 instead of p1, p2 and p3. And that worked. But if I run this code.

The thing that this program does is to sort two arrays, and sets them in correct order.

Arr2 = [2,5,6,8]

Arr1_Length = len(Arr1)
Arr2_Length = len(Arr2)

FinishArr_Length = Arr1_Length + Arr2_Length

FinishArr = []

p1 = 0
p2 = 0
p3 = 0

print(FinishArr)
print(FinishArr_Length)
print(Arr1[p1])
print(Arr2[p2])

while p3 < FinishArr_Length:
    if Arr1[p1] < Arr2[p2]:
        FinishArr.append(Arr1[p1])
        p1 += 1
    else:
        FinishArr.append(Arr2[p2])
        p2 += 1
    p3 += 1

print(FinishArr)

I get this error:

Traceback (most recent call last):
  File "Test.py", line 21, in <module>
    if Arr1[p1] < Arr2[p2]:
IndexError: list index out of range

Upvotes: 3

Views: 102

Answers (1)

Pratik
Pratik

Reputation: 1399

You have to check that p1 and p2 don't exceed their respective array's length:

while p1<Arr1_Length and p2<Arr2_Length:
    if Arr1[p1] < Arr2[p2]:
        FinishArr.append(Arr1[p1])
        p1 += 1
    else:
        FinishArr.append(Arr2[p2])
        p2 += 1
    p3 += 1

After that, you have to check if elements of Arr1 or Arr2 are remaining and push the remaining values in FinishArr.

if p1<Arr1_Length:
    while p1<Arr1_Length:
        FinishArr.append(Arr1[p1])
        p1 += 1
if p2<Arr2_Length:
    while p2<Arr2_Length:
        FinishArr.append(Arr2[p2])
        p2 += 1

Upvotes: 5

Related Questions