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
?
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]
Different lines, but also more readable
a = [5, 3, 2, 8, 1, 4]
b = sorted([item for item in a if item%2 != 0])
odd_int = 0
for i in range(len(a)):
if a[i] %2 != 0:
a[i] = b[odd_int]
odd_int += 1
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])
def sort_array(source_array):
odd_numbers = sorted([n for n in source_array if n%2!=0])
c = 0
res = []
for i in source_array:
if i %2!=0:
res.append(odd_numbers[c])
c += 1
else:
res.append(i)
return res