Home > Mobile >  How to return a new list that contains just odd elements from data using only recursion
How to return a new list that contains just odd elements from data using only recursion

Time:03-29

I have been asked to:

Write a function odds(data) that takes a list of ints, data, as a parameter and returns a new list that contains just the odd elements from data, i.e. those elements that are not exactly divisible by two. Your code must not use for or while and must not import anything.

This is my current code:

def odds(data):
    """Returns a new list that contains just the odd elements from the data"""
    odd_nums = []
    if len(data) == 1:
        return []
    
    if data[0] % 2 != 0:   
        odd_nums.append(data[0])
    return odds(data[1:])

Test codes:

print(odds(\[0, 1, 12, 13, 14, 9, -11, -20\]))

---\> \[1, 13, 9, -11\]

I am not sure how to recursively keep adding to the odd_nums list.

CodePudding user response:

def odds(data):
    if not data:
        return []
    head = [ data[0] ] if data[0]%2==1 else []
    if len(data)>1:
        return head   odds (data[1:])
    else:
        return head
    
print(odds([0, 1, 12, 13, 14, 9, -11, -20]))

You almost had it. Just combine lists. potentially empty lists are fine.

CodePudding user response:

Using python filter function, that takes a function to use as filter (True for those who will continue to be in the list), and the list to be filtered.

list(filter(lambda x: x%2==0, data))
  • Related