Sort / group odd and even numbers in an odd or even segregated list

I have an unsorted list of even and odd numbers. I need to separate the odd and even numbers in sorted order.

For instance:

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

Expected Result:

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

My program for highlighting 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 a list using insertion sort, cannot get the correct output. Any way to sort it easy

+4
source share
7 answers

Using the smart key function for list.sort / sorted :

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

[0, n], - [1, n], .

+3

n%2 (n modulo 2), 0 1 , :

L = [5,6,4,7,11,14,12,1,3]
out = sorted(L, key = lambda n:(n%2, n))

print(out)
# [4, 6, 12, 14, 1, 3, 5, 7, 11]

, , , .

...

+1

, :

lst = [5,6,4,7,11,14,12,1,3]
even = sorted([i for i in lst if i%2 == 0])
odd = sorted([i for i in lst if i%2])
print(even + odd)

filter, lambda:

lst = [5,6,4,7,11,14,12,1,3]
lst.sort()

even = list(filter(lambda x: not x%2, lst))
odd = list(filter(lambda x: x%2, lst))

print(even + odd)
0

>>> arr = [5,6,4,7,11,14,12,1,3]
>>> evens = sorted([e for e in arr if e % 2 ==0])
>>> odds = sorted([e for e in arr if e % 2 !=0])
>>> print(evens + odds)
[4, 6, 12, 14, 1, 3, 5, 7, 11]
0

:

import numpy as np
l = [5,6,4,7,11,14,12,1,3]
l_sort = np.sort(l) #sorting elements of the list
evens = list(filter(lambda x: x%2==0, l_sort)) #extract even elements 
odds = list(filter(lambda x: x%2!=0, l_sort)) #extract even elements
out = evens + odds 
0

If you are happy to use a third-party library, you can use Boolean indexing with numpy.

numpy.lexsortsorts in the opposite way, that is, it counts A % 2to A:

import numpy as  np

A = np.array([4,6,12,14,1,3,5,7,11])

res = A[np.lexsort((A, A % 2))]

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

Related: Why NumPy instead of Python Lists?

0
source

I suggest this if you want to avoid using external libraries:

def even_odd_sort(list):
evens=[]
odds=[]
for i in list:
    if(i%2==0):
        evens.append(i)
    else:
        odds.append(i)
evens.sort()
odds.sort()
return evens+odds
0
source

Source: https://habr.com/ru/post/1696213/


All Articles