def iFilter(fn, li):
result = []
for x in li:
if fn(x):
result.append(x)
return result
def rFilter(fn, li):
if len(li) == 0: return []
head, *tail = li
if fn(head):
return [head] + rFilter(fn, tail)
return rFilter(fn, tail)
li = [1, 2, 3, 4, 5, 6]
print('input list:', li)
odds = iFilter(lambda x: x % 2, li)
evens = iFilter(lambda x: not (x % 2), li)
print('\nusing iterative filter function')
print('odds :', odds)
print('evens:', evens)
print('\nusing recursive filter function')
odds = rFilter(lambda x: x % 2, li)
evens = rFilter(lambda x: not (x % 2), li)
print('odds :', odds)
print('evens:', evens)
To embed this project on your website, copy the following code and paste it into your website's HTML: