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)
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1443
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)
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1443
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 6 guests