Kee
Kee

Reputation: 163

Get even numbers and odd numbers in order in list

An example:

def get_evens_at_back(a_list):
    if not a_list:
      return []
    if a_list[0] % 2 == 1:
      return [a_list[0]] + get_evens_at_back(a_list[1:])
    return get_evens_at_back(a_list[1:])

    print("1.", get_evens_at_back([-1, 2, -3, 4, -2, 3, 5]))
    print("2.", get_evens_at_back([1, 2, -3, 4, 7, 4, -6, 3, -1]))
    print("3.", get_evens_at_back([-4, -2, 6, 8, 6, 2]))
    print("4.", get_evens_at_back([-3, -1, 3, 1, 7, 9]))
    print("5.", get_evens_at_back([]))

output:

 1. [-1, -3, 3, 5]
 2. [1, -3, 7, 3, -1]
 3. []
 4. [-3, -1, 3, 1, 7, 9]
 5. []

I'm trying get a new list with all the odd numbers from the list (in sorted order) at the front and all the even numbers from the list (in sorted order) at the back of the list. If the list is empty, the function should return an empty list.I'm not sure how to fix it.

expected:

 1. [-3, -1, 3, 5, -2, 2, 4]
 2. [-3, -1, 1, 3, 7, -6, 2, 4, 4]
 3. [-4, -2, 2, 6, 6, 8]
 4. [-3, -1, 1, 3, 7, 9]
 5. []

Upvotes: 1

Views: 1836

Answers (2)

Casey Kuball
Casey Kuball

Reputation: 7955

Here's a fairly readable version, that uses the filter built-in function to get all the odd/even values in separate lists, sorts those lists, and then combines them (using the list + operator):

def is_even(i):
    return (i % 2) == 0

def is_odd(i):
    return (i % 2) != 0

def get_evens_at_back(l):
    odds = list(filter(is_odd, l))
    evens = list(filter(is_even, l))

    return sorted(odds) + sorted(evens)

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can use sorted with a 2-tuple, putting the odd numbers first and then sorting by the magnitude of the numbers for each category:

>>> lst = [1, 2, -3, 4, 7, 4, -6, 3, -1]
>>> sorted(lst, key=lambda x: (x % 2 == 0, x))
[-3, -1, 1, 3, 7, -6, 2, 4, 4]

Upvotes: 3

Related Questions