A factorial one-line function (Python)

vegaseat 0 Tallied Votes 4K Views Share

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
'''
jamesjohnson25 0 Newbie Poster

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

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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 0 Newbie Poster

I didn't understand this

mathwizurd 0 Newbie Poster

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

Tcll 66 Posting Whiz in Training Featured Poster

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 ;)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.