Exercise: Filtering
Define a function myfilter(test, seq) that removes items in seq that return False for test.
def myfilter(test, seq):
"""Filter seq by test.
>>> myfilter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6])
[2, 4, 6]
"""
Notes
- Solve it with
whileand also withproc_seqorprocfrom funcutils. - The sequence can be implemented as a
tupleor alist. - If you use
tuples, you can only manipulate them using slicing and concatenation (+). - Lists allow for in-place manipulation.
- You can try versions with in-place manipulation (for list based solutions), but make sure you can solve the problem wihhout in-place manipulation.
Library
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]