Reputation: 35
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!
Upvotes: 0
Views: 45
Reputation: 118
Two ways to sort an array that I know in python
sort()
method to your array as
MyArray.sort()
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)
Upvotes: 1
Reputation: 564
You're making two mistakes.
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.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)
Upvotes: 1