Issue
Why does this code print 2? I'm having a hard time wrapping my head around the order of the calls and what happens when the code runs. I'd like to know what's going on here, thanks!
The code:
mia = lambda dan: lambda john: list(john)[dan]
john = lambda mia: lambda dan: filter(dan, map(lambda x: x % 2 + 1, mia))
ta = mia(-1)(john([3, 6, 9, 12, 15])(lambda f: f % 3))
print(ta)
Solution
This is some kind of obfuscated way to perform a simple task:
- check if numbers in a list are odd or even and map 1, 2 accordingly
- filter the previous output if this is not a multiple of 3 (which is always True)
- 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
Answered By - mozway Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.