Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting/grouping odd and even numbers in odd and even segregated list

Tags:

python

sorting

I have a unsorted list of number with even and odd. I need to segregate odd and even numbers in sorted order.

For example:

List = [5,6,4,7,11,14,12,1,3]

Expected output :

[4,6,12,14,1,3,5,7,11]

My program to segregate the odd and even numbers.

L = [5,6,4,7,11,14,12,1,3]
def segregateEvenOdd(L):
    left,right = 0,len(L)-1
    while left < right:
        while (L[left]%2==0 and left < right):
            left += 1
        while (L[right]%2 == 1 and left < right):
            right -= 1
        if (left < right):
            L[left],L[right] = L[right],L[left]
            left += 1
            right = right-1

print segregateEvenOdd(L)

output : [12, 6, 4, 14, 11, 7, 5, 1, 3]

I am trying to sort the list using insertion sort, couldn't get right output. Any way to sort this easily

like image 617
PGS Avatar asked Jan 02 '23 12:01

PGS


1 Answers

Using a key function for list.sort / sorted:

>>> list(sorted(lst, key=lambda x: [x % 2, x]))
[4, 6, 12, 14, 1, 3, 5, 7, 11]

maps even numbers n to the value [0, n], and odd numbers n to the value [1, n], so that even numbers come first according to natural ordering of list items, i.e. [0, ...] comes before [1, ...].

like image 200
fferri Avatar answered Jan 14 '23 08:01

fferri