Sort odd numbers in a list
How can I sort the ascending odd numbers in a list of integers, but leaving the even numbers in their original places?
Example:
sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
My code:
def sort_array(source_array):
odd_numbers = [n for n in source_array if n%2!=0]
odd_numbers = sorted(odd_numbers)
How to switch the indices of odd numbers in source_array
with those of odd_numbers
?
source to share
It looks like you're almost there - you can make your sorted odd numbers iterable and rebuild the original list with either the original even number or the next sorted odd number, like this:
>>> data = [5, 3, 2, 8, 1, 4]
>>> odds = iter(sorted(el for el in data if el % 2))
>>> [next(odds) if el % 2 else el for el in data]
[1, 3, 2, 8, 5, 4]
source to share
If you are open to using numpy, you can get the indices of odd numbers using np.where
, sort the odd numbers, and update the array using the previously obtained indices assigning the sorted array of odd numbers:
import numpy as np
a = np.array([5, 3, 2, 8, 1, 4])
ind = np.where(a%2) # get indices of odd items
a[ind] = np.sort(a[ind]) # update items at indices using sorted array
print(a)
# array([1, 3, 2, 8, 5, 4])
source to share