Here lambda is used to create a one-line function for factorials.

``````''' factorial_oneliner.py
get the factorial of integer n
tested with Python27 and Python34
'''

fact = lambda n: [1,0][n>1] or fact(n-1)*n

# test it ...
print(fact(53))

''' result ...
second line is mpmath result for comparison
4274883284060025564298013753389399649690343788366813724672000000000000
4274883284060025564298013753389399649690343788366813724672000000000000
'''``````
5
Contributors
6
Replies
61
Views
3 Years
Discussion Span
Last Post by vegaseat

Can you explain me how this part "[1,0][n>1]" works ?

In Python True is 1 and False is 0
If n gets to be less than 1 the whole thing evaluates to
[1, 0][0] the element at index 0, which is the 1 (True), the exit condition for the recursive function.

I didn't understand this

Miocunard, it's useful to look at this starting with n.

``````fact = lambda n: [1,0][n>1] or fact(n-1)*n
``````

Let's say n = 3, when you go through it, [0,1][3 > 1] -> [0,1][1] = 0. When you return (a or b), it returns a if it's true, otherwise it returns b. Now, fact(3) becomes fact(2) x 3.

When n = 2, the same thing happens: the first part equals 0, and fact(2) becomes fact(1) x 2 = fact(2).

When n = 1, [1,0][n>1] becomes [1,0][0], because n == 1, so it fact(1) = 1.

Now, you substitute it back: fact(2) = fact(1) * 2 = 1 * 2. fact(3) = fact(2) * 3, or 2 * 3 = 6

Edited by mathwizurd: Fixed the wording

this is very nice, I'm probably one of the biggest fans of 1-liners out there, so yah, good job :)

just to note, you could always invert instead of index ;)
and do we really need a lambda??

``````>>> def fact(n): return (n>1)^1 or fact(n-1)*n

>>> fact(53)
4274883284060025564298013753389399649690343788366813724672000000000000L
``````

^now we're not creating a list object to index ;)

@MIOCUNARD,
let's hope you are not building yourself up to be a signature spammer.

Edited by vegaseat

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.