We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Currying Practice

Remember, currying is when we take a function that accepts multiple arguments:

final_volume: int = box_volume(3, 4, 5)
print(final_volume)
# 60

and convert it into a series of functions that each accept a single argument:

final_volume: int = box_volume(3)(4)(5)
print(final_volume)
# 60
  • box_volume(3) returns a new function that accepts a single integer and returns a new function
  • box_volume(3)(4) returns another new function that accepts a single integer and returns the final result
  • box_volume(3)(4)(5) returns the final result

Here's another way of calling it, where each function is stored in a variable before being called:

with_length_3 = box_volume(3)
with_len_3_width_4 = with_length_3(4)
final_volume: int = with_len_3_width_4(5)
print(final_volume)
# 60

Here are the function definitions:

from collections.abc import Callable


def box_volume(length: int) -> Callable[[int], Callable[[int], int]]:
    def box_volume_with_len(width: int) -> Callable[[int], int]:
        def box_volume_with_len_width(height: int) -> int:
            return length * width * height

        return box_volume_with_len_width

    return box_volume_with_len

Assignment

Doc2Doc needs to be able to find the number of lines in a document that contain a specific sequence of characters. For example, given the following document:

aaaa
bbbb
ccdd
aabb

How many lines contain the sequence aa? The answer is 2: aaaa and aabb.

Complete the lines_with_sequence function. It should return a series of curried functions so it can be called like this:

num_lines: int = lines_with_sequence(char)(length)(doc)

The "sequence" is generated by the first with_char that has been provided for you. It works like this:

Character Length Sequence
"a" 3 "aaa"
"b" 2 "bb"
"*" 4 "****"

You need to define and return a second curried function. I called mine with_length. It should accept the final parameter, a doc string, and return the number of lines that contain the sequence.