Home > database >  How to sort a list into even then odd numbers using recursion when the function can only call itself
How to sort a list into even then odd numbers using recursion when the function can only call itself

Time:11-23

The function takes in a list of integers and returns a list of the same elements sorted into the order of even integers then odd ones. Im struggling with implementing a recursive function to complete it even though I am able to solve this using a for loop.

def sort(lst: list[int]) -> list[int]:
    l1 = []
    l2 = []
    for i in lst:
        if i % 2 == 0:
            l1.append(i)
        else:
            l2.append(i)
    x = l1   l2
    return x
def eto(lst: list[int]) -> list[int]:

    if len(lst) == 1
        return lst
    else:
        y = lst[0]
        x = lst[1:]
        return(eto(x))

I'm not sure how to proceed from here.

CodePudding user response:

I suppose we are allowed to reorder the odd numbers, as long as they are in the second part of the list. I completed your proposition:

def eto(lst: list[int]) -> list[int]:

    if len(lst) <= 1:
        return lst

    head = lst[0]
    tail = lst[1:]
    if head % 2 == 0:
        return [head]   eto(tail)
    return eto(tail)   [head]
  • Related