Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

def odds(data):
    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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading