263.10 Data Engineering - Functional Programming

This mission doesn’t work on my jupyter notebook.
Is Compose is custom function or a library. Please explain

from functools import reduce
lines = read('example_log.txt')
ip_addresses = partial(map,lambda x: x.split()[0])
filtered_ips = partial(filter,lambda x: int(x.split('.')[0]) <= 20)
count = partial(reduce,lambda x, _: 2 if isinstance(x, str) else x + 1)
composed = compose(
    ip_addresses,
    filtered_ips,
    count
)
counted = composed(lines)
ratio = count_filtered / count_all

NameError: name 'compose' is not defined

Hey, Nishad.

Apologies for this bad experience. We are creating this function in the background for you. Here’s its definition:

def compose (*functions):
    def inner(arg):
        for f in functions:
            arg = f(arg)
        return arg
    return inner 

What this function does is return another function, locally called inner, that applies each of the functions in the argument of compose successively. In the “Learn” section’s example,

compose(add_two, multiply_by_four, subtract_seven)

is equivalent to

lambda x: subtract_seven(multiply_by_four(add_two(x)))

Thanks, Bruno! This helps. A still little complex to understand in action.

No worries :slight_smile:

Given that this question started out as a problem with the Dataquest platform (we are doing something under the hood to which you don’t have access), and now you want help regarding a technical matter, I’ll ask you to ask another question detailing what it is that you don’t understand so that we can better help you.