반응형
Task
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.
Examples
[7, 1] => [1, 7]
[5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]
Solution:
def sort_array(source_array):
a,b = [],[]
for i, v in enumerate(source_array):
if v%2==1:
a.append(v)
b.append(i)
for v,i in zip(sorted(a), sorted(b)):
source_array[i] = v
return source_array
Other Solution: use pop
def sort_array(arr):
odds = sorted((x for x in arr if x%2 != 0), reverse=True)
return [x if x%2==0 else odds.pop() for x in arr]
Other Solution: use iter
def sort_array(source_array):
odds = iter(sorted(v for v in source_array if v % 2))
return [next(odds) if i % 2 else i for i in source_array]
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Descending Order (0) | 2022.08.05 |
---|---|
Small enough? - Beginner (0) | 2022.08.03 |
Form The Minimum (0) | 2022.08.02 |
Make a function that does arithmetic! (0) | 2022.07.31 |
Printer Errors (0) | 2022.07.31 |