''' 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
'''

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.

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 1 Year Ago 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 1 Year Ago by vegaseat

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.