Here is the question:
You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.
Here is my code:
def sort_array(source_array):
odd_ints = []
for i in source_array:
if i % 2 == 1:
odd_ints.append(i)
odd_ints.sort()
else:
pass
counter = 0
for x in source_array:
if x % 2 == 1:
x = odd_ints[counter]
counter += 1
print(source_array)
else:
pass
return source_array
When I test it, it does this:
>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
For some reason, I can't re-assign the variable x
in the function to odd_ints
in ascending order. Would anyone know the problem in my code?
You just need to save the positions of the odd integers as well to replace them:
def sort_array(source_array):
odd_ints = []
positions = []
counter = 0 #need counter to get positions
for i in source_array:
if i % 2 == 1:
odd_ints.append(i) #keep the values
positions.append(counter) #keep the position
counter += 1
odd_ints.sort() #sort for replacement
counter2 = 0 #need second counter to place sorted list
for pos in positions:
source_array[pos] = odd_ints[counter2] #place the sorted values
counter2 += 1
return source_array
print(sort_array([5, 3, 2, 8, 1, 4]))
Output:
[1, 3, 2, 8, 5, 4]