Search code examples
pythonlistfunctionlisp

How to split a list only using car, cdr, cons and other functions (python)


we need to be able to make a function that has 1 list as an input. We need to split the even numbers from the uneven numbers and put them in seperate lists. We are not permitted to make a second list and should be able to solve it only using recursion, and with car, cdr, cons, ... .

This is what I already have:

def split_list(list_a):
    if null(list_a):
        return []
    elif not even(car(list_a)):
        return cons(car(list_a), split_list(cdr(list_a)))
    else:
        return cons(splits_lijst(cdr(list_a)), car(list_a))
print(split_list([1, 2, 3, 4]))

I became the output: [1, 3, 4, 2]

While it should be: [1, 3][2, 4]

I really have no clue how to do this without making a secondary list.

Just to be clear, the functions in the function 'split_list' are car, cdr, cons, null and even. Here you see the contents of those functions:

def car(a_list):
    return a_list[0]

def cdr(a_list):
    return a_list[1:]

def null(a_list):
    return True if len(a_list) == 0 else False

def cons(a, b):
    new_list = []
    if type(a) is list:
        for item in a:
            new_list.append(item)
    else:
        new_list.append(a)
    if type(b) is list:
        for item in b:
            new_list.append(item)
    else:
        new_list.append(b)
    return new_list

def even(x):
    if x == 1:
        return False
    elif x == 0:
        return True
    else:
        return even(x-2)

Solution

  • You need a way to make two lists during your iteration of one list. The best way to do that is to make a function that takes 3 arguments. one for the input and 2 for the two output lists, often called accumulators.

    The logic would be to return a list of the two accumulators when you have reached the end of the list. If not you check the element for evenness and recurse by adding it to the even accumulator. If not you recurse by adding the element to the odd accumulator.