PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] Why does this code print 2? What does it do?

 September 18, 2022     dictionary, filter, lambda, printing, python     No comments   

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:

  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



Answered By - mozway
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing