Sebastian S
Sebastian S

Reputation: 337

Recursive functions and lists

Im still studying old tests and got truble with this recursive task.

Write a recursive function "cut" that takes a list and a number as argument and retuns a list containing all numbers from the list that is less than the number given in the argument.

Example:

>>> cut([1,5,2,8,7,4,0,9], 5)

[1,5,2,4,0]

Here is what I have come up with and its not working at all. I dont know how to make the new list or how to do the alternative if possible delete the numbers that is < given argument

def cut(lista, tal):

    a = 0
    if not lista:
        return a
        print a 
    if lista[0] <= tal:
       a = a + lista[0]

    cut(lista[1:], tal)

Any Ideas for this? I need basics, not advanced functions. I've been staring at this for over an hour now getting nowhere :s

Upvotes: 0

Views: 55

Answers (1)

ferhatelmas
ferhatelmas

Reputation: 3978

Actually, you're close but you need to initialize a with [] and concatenate recursive result to a (what is returned from inside cut). Also, if you'd like to see list, first print then return. Otherwise, it's unreachable.

def cut(ls, n):
    if not ls:  # base 
        return []
    return (ls[:1] if ls[0] < n else []) + cut(ls[1:], n)  # peeling + rest

Note that in the description it's written less than given number but your example contains equal result, too. If needed, change it to ls[0] <= n.

Upvotes: 1

Related Questions