I am attempting a Python practice problem on GeeksForGeeks, but my code raises IndexError every time.
The problem is as follows:
Given a sorted array of positive integers
arr, and an integer
nwhich represents the length of
arr, your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
Note: Modify the original array itself.
My code however raises
IndexError: list index out of range
Here is my code:
def rearrange(arr, n): arr1,arr2 = sorted(arr[:(n//2)]), sorted(arr[(n//2):],reverse=True) arr.clear() for i in range(n): arr.append(arr2); arr2.pop(0) arr.append(arr1); arr1.pop(0)
Here is the error:
File "/home/4c7d0350d40e21b84be527508f21cb47.py", line 9, in rearrange arr.append(arr2); arr2.pop(0) IndexError: list index out of range
I don’t understand why this is happening. Can anyone provide an explanation?
In your code, both arr1 and arr2 are initialized with a length of
n//2. In your for loop:
for i in range(n): arr.append(arr2); arr2.pop(0) arr.append(arr1); arr1.pop(0)
You access the first element and remove the first element
n times! This requires there to be
n elements in
arr2, but there are not this many. So, you keep trying to access the 0 index element of the array even after the array is empty, which causes this error.