|
| 1 | +# Mixed sorting |
| 2 | + |
| 3 | +""" |
| 4 | +Given a list of integers nums, sort the array such that: |
| 5 | +
|
| 6 | +All even numbers are sorted in increasing order |
| 7 | +All odd numbers are sorted in decreasing order |
| 8 | +The relative positions of the even and odd numbers remain the same |
| 9 | +Example 1 |
| 10 | +Input |
| 11 | +
|
| 12 | +nums = [8, 13, 11, 90, -5, 4] |
| 13 | +Output |
| 14 | +
|
| 15 | +[4, 13, 11, 8, -5, 90] |
| 16 | +Explanation |
| 17 | +
|
| 18 | +The even numbers are sorted in increasing order, the odd numbers are sorted in |
| 19 | +decreasing number, and the relative positions were |
| 20 | +[even, odd, odd, even, odd, even] and remain the same after sorting. |
| 21 | +""" |
| 22 | + |
| 23 | +# solution |
| 24 | + |
| 25 | +import unittest |
| 26 | + |
| 27 | + |
| 28 | +def mixed_sorting(nums): |
| 29 | + positions = [] |
| 30 | + odd = [] |
| 31 | + even = [] |
| 32 | + sorted_list = [] |
| 33 | + for i in nums: |
| 34 | + if i%2 == 0: |
| 35 | + even.append(i) |
| 36 | + positions.append("E") |
| 37 | + else: |
| 38 | + odd.append(i) |
| 39 | + positions.append("O") |
| 40 | + even.sort() |
| 41 | + odd.sort() |
| 42 | + odd.reverse() |
| 43 | + j,k = 0,0 |
| 44 | + for i in range(len(nums)): |
| 45 | + if positions[i] == "E": |
| 46 | + while j < len(even): |
| 47 | + sorted_list.append(even[j]) |
| 48 | + j += 1 |
| 49 | + break |
| 50 | + else: |
| 51 | + while k < len(odd): |
| 52 | + sorted_list.append(odd[k]) |
| 53 | + k += 1 |
| 54 | + break |
| 55 | + |
| 56 | + return sorted_list |
| 57 | + |
| 58 | + |
| 59 | +# DO NOT TOUCH THE BELOW CODE |
| 60 | + |
| 61 | + |
| 62 | +class TestMixedSorting(unittest.TestCase): |
| 63 | + def test_1(self): |
| 64 | + self.assertEqual(mixed_sorting( |
| 65 | + [8, 13, 11, 90, -5, 4]), [4, 13, 11, 8, -5, 90]) |
| 66 | + |
| 67 | + def test_2(self): |
| 68 | + self.assertEqual(mixed_sorting([1, 2, 3, 6, 5, 4]), [5, 2, 3, 4, 1, 6]) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + unittest.main(verbosity=2) |
0 commit comments