

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Functions As Values
incomplete
2: Anonymous Functions
incomplete
3: First-Class and Higher-Order Functions
incomplete
4: Map
incomplete
5: Filter
incomplete
6: Reduce
incomplete
7: Map, Filter, and Reduce Review
incomplete
8: Zip
incomplete
9: Higher-Order Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
"Map," "filter," and "reduce" are three commonly used higher-order functions in functional programming.
In Python, the built-in map function takes a function and an iterable (often a list) as inputs. It returns an iterator that applies the function to every item, yielding the results.
With map, we can operate on lists without using loops and nasty stateful variables. For example, given this code:
def square(x: int) -> int:
return x * x
nums: list[int] = [1, 2, 3, 4, 5]
squared_nums: list[int] = []
for num in nums:
num_squared: int = square(num)
squared_nums.append(num_squared)
print(squared_nums)
# [1, 4, 9, 16, 25]
We could use map instead, like this:
from collections.abc import Iterator
def square(x: int) -> int:
return x * x
nums: list[int] = [1, 2, 3, 4, 5]
squared_nums: Iterator[int] = map(square, nums)
print(list(squared_nums))
# [1, 4, 9, 16, 25]
map() returns a "map object," so the list() type constructor is needed to convert it back into a standard list.
Markdown supports two different styles of bullet points, - and *. We prefer *, so, we need a function to convert any - bullet points to * bullet points.
Complete the change_bullet_style function. It takes a document (a string) as input, and returns a single string as output. The returned string should have any lines that start with a - character replaced with a * character.
For example, this:
- This is a bullet
- This is a bullet
Becomes:
* This is a bullet
* This is a bullet
Use the built-in map function to apply the provided convert_line function to each line of the input string. Use .split() and .join() to split the document into a list of lines, and then join the lines back together. This should preserve the original line breaks. Don't use the .replace() string method.
Examples of split and join:
# my_document is a string with newlines
lines_list: list[str] = my_document.split("\n")
rejoined_doc: str = "\n".join(lines_list)