(PYTHON- NO LOOPS)
Complete the body of the following function filter_odd(L) which uses structural recursion, consumes a list of natural numbers, and returns a list of numbers that contains only the odd numbers from the original list. Do not use abstract list functions.
if L == []:
return []
else:
if L[0] % 2 != 0:
else:
Explanation in comments-
Code-
def filter_odd(l):
if l==[]: #if list is empty then return empty
return []
if l[0] % 2 == 1: #checking first item of list
return [l[0]] + filter_odd(l[1:]) # if true then return first item
along with recusive call of remaining list
return filter_odd(l[1:]) #otherwise function is called recursively
for remaining elements
#Sample Run
mylist = [1,5,7,6,2,9,10,2,3,11]
print(filter_odd(mylist))
Get Answers For Free
Most questions answered within 1 hours.