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
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, ...]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With