Why does this code print 2? What does it do?

Solution 1:

This is some kind of obfuscated way to perform a simple task:

  1. check if numbers in a list are odd or even and map 1, 2 accordingly
  2. filter the previous output if this is not a multiple of 3 (which is always True)
  3. take the last item of the previous output

In summary, this output 2 if the last number of the input is odd and 1 otherwise.

This could be simplified to:

list(map(lambda x: x % 2 + 1, [3, 6, 9, 12, 15]))[-1]

or, keeping the useless filter:

list(filter(lambda f: f % 3, map(lambda x: x % 2 + 1, [3, 6, 9, 12, 15])))[-1]

This is using a functional approach in which the functions return functions instead of values. In addition the local variables have names designed to be confusing (mia in john has nothing to do with the mia function)

Interestingly, mia is equivalent to operator.itemgetter

Solution 2:

It does a lot less than it looks like.

To simplify, turn the lambda expressions into def statements.

def mia(dan):
    def inner(john):
        lst = list(john)
        return lst[dan]
    return inner

def john(mia):
    def inner(dan):
        mp = map(lambda x: x % 2 + 1, mia)
        return filter(dan, mp)
    return inner

To simplify further, separate your function calls.

# just return the inner function
john_inner_func = john([3, 6, 9, 12, 15])
# first map element % 2 + 1 to each element of the given array
# this results in [2, 1, 2, 1, 2]
# next it filters all truthy (non-zero) values of the result of element % 3. 
# Since all are positive and less than 3 the result is the same
# [2, 1, 2, 1, 2]
john_filter_result = john_inner_func(lambda f: f % 3)
# just return the inner function
mia_inner_func = mia(-1)
# return the -1 index of the filter result as a list
# this gives the last element, or 2
ta = mia_inner_func(john_filter_result)
print(ta)