Conditional operator in Python?
Mikael Olofsson
mikael at isy.liu.se
Tue Sep 4 02:57:47 EDT 2001
On 04-Sep-2001 thp at cs.ucr.edu wrote:
> Terry Reedy <tjreedy at home.com> wrote:
>
> : <thp at cs.ucr.edu> wrote in message news:9n1hr7$7op$1 at glue.ucr.edu...
> :> I hate writing:
> :>
> :> factorial = lambda x : (x<=1 and [1] or [x*factorial(x-1)])[0]
>
> : Since 1 != 0, quite dependably, you do not need to. try "x<=1 and 1 or
> : x*factorial(x-1)"
Interesting. If I were to write a factorial using a lambda, I would probably
have written
factorial = lambda x: reduce(lambda a,b:a*b,range(1,x+1))
or
import operator
factorial = lambda x: reduce(operator.__mul__, range(1,x+1))
Those two throw exceptions for non-positive input, which I prefer. But
regrettably, they give rather stupid error messages.
/Mikael
-----------------------------------------------------------------------
E-Mail: Mikael Olofsson <mikael at isy.liu.se>
WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael
Phone: +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date: 04-Sep-2001
Time: 08:43:03
/"\
\ / ASCII Ribbon Campaign
X Against HTML Mail
/ \
This message was sent by XF-Mail.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com
More information about the Python-list
mailing list