Rewrite this lambda expression without lambda or variables.

This is the place for queries that don't fit in any of the other categories.

Rewrite this lambda expression without lambda or variables.

Postby russ » Mon Mar 04, 2013 9:28 am

Just a small problem I was thinking about for a good few minutes before I decided to use lambda. It's part of a one liner obfuscated code snippet.

Code: Select all
lambda x : x if x >= 2 else 2


I thought there might be a way to do this as an expression using nothing but arithmetic operators, or at most divmod.
russ
 
Posts: 18
Joined: Sat Mar 02, 2013 8:59 am

Re: Rewrite this lambda expression without lambda or variabl

Postby micseydel » Mon Mar 04, 2013 9:50 am

max(x, 2)
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
micseydel
 
Posts: 2997
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Rewrite this lambda expression without lambda or variabl

Postby russ » Mon Mar 04, 2013 9:58 am

:D that's brilliant!

So in future I can use the following cases:

Code: Select all
max(x, n) --> (x if x >= n else n) --> floor
min(x, n) --> (x if x <= n else n) --> ceiling
min(max(x, a), b) --> x if a <= x <= b else a if x < a else b --> floor and ceiling


--edit--
added in the answer for the third case
Last edited by russ on Mon Mar 04, 2013 10:14 am, edited 1 time in total.
russ
 
Posts: 18
Joined: Sat Mar 02, 2013 8:59 am

Re: Rewrite this lambda expression without lambda or variabl

Postby micseydel » Mon Mar 04, 2013 10:11 am

I believe the last one is equivalent to
Code: Select all
min(max(x, a), b)
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
micseydel
 
Posts: 2997
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 9 guests