

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
The built-in functools.reduce() function takes a function and a list of values, and applies the function to each value in the list, accumulating a single result as it goes.
# import functools from the standard library
import functools
def add(sum_so_far: int, x: int) -> int:
print(f"sum_so_far: {sum_so_far}, x: {x}")
return sum_so_far + x
numbers: list[int] = [1, 2, 3, 4]
sum: int = functools.reduce(add, numbers)
# sum_so_far: 1, x: 2
# sum_so_far: 3, x: 3
# sum_so_far: 6, x: 4
# 10 doesn't print, it's just the final result
print(sum)
# 10
Notice that we're passing the function add without the ()! It means that reduce will take care of execution and pass the parameters for you. Think of passing add like handing someone a recipe (the instructions), instead of the finished dish (the result of the execution).
Complete the join and the join_first_sentences functions.
doc_so_far accumulator string – similar to the sum_so_far variable in the example above.sentence string – this is the next string we want to add to the accumulator.doc: str = "This is the first sentence"
sentence: str = "This is the second sentence"
print(join(doc, sentence))
# This is the first sentence. This is the second sentence
nUse list slicing to get the first n sentences.
Here's an example of the expected behavior:
joined: str = join_first_sentences(
[
"This is the first sentence",
"This is the second sentence",
"This is the third sentence",
],
2,
)
print(joined)
# This is the first sentence. This is the second sentence.