Home > database >  How to sort the elements of a list based off associated index python
How to sort the elements of a list based off associated index python

Time:11-27

I am looking to sort MyArray[] of size n elements so that MyArray[n] = n. If the element is missing it should be replaced with a -1. Here is an example: Input : MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]

MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
MyArrayNew = []
for n in MyArray:
    if n <= len(MyArray):
         MyArrayNew[n] = n
    else:
         MyArrayNew[n] = -1
print(MyArrayNew)

Here is my code thus far, any pointers on how to properly code this would be greatly appreciated!

CodePudding user response:

You're making two mistakes.

  1. You use n as an index as well as the value. From the for loop it can be seen that n is the value of each element in the list MyArray. But later on you use this as an index when you call MyArrayNew[n]. When n is -1 there is propably some things that happen that you do not want.
  2. lists indices can only be changed if they already exist. MyArrayNew starts of empty, so you can't say: change the third index to three, because the third index doesn't exist yet.

There are many approaches to solve this problem. I'll give one:

To solve the second problem I suggest appending instead of assigning indices. To solve the first problem, you could use for i in range len(arr):, but I prefer enumerate.

I'll also approach it the other way around: cycle through the indices and check if it should be its index value, or -1.

This results in the following code:

MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
MyArrayNew = []
for index, value in enumerate(MyArray):
    if index in MyArray:
        MyArrayNew.append(index)
    else:
        MyArrayNew.append(-1)

print(MyArrayNew)

CodePudding user response:

Two ways to sort an array that I know in python

  1. for an inplace sorting: apply the sort() method to your array as MyArray.sort()
  2. The second way is to use nested FOR ... LOOP and compare values in the array from Index 0 to the final item. I normally use a temp value to keep the previous value, compare it with the current, and swap the values according to the size. The example code below
     for i in range(len(MyArray)):
            #outer loop
            for j in range(i 1, len(MyArray)):
                #start from i 1,  why because you always want to compare the 
                     previous element with the current element in the outer loop
                if(MyArray[i] > MyArray[j]):
                    temp = MyArray[i]
                    MyArray[i] = MyArray[j]
                    MyArray[j] = temp
         print(MyArray)   
  • Related