Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 270
Fredrikj31 Avatar asked Sep 24 '26 16:09

Fredrikj31


1 Answers

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
like image 76
Pratik Gandhi Avatar answered Sep 27 '26 04:09

Pratik Gandhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!