The Evolution of a Python Programmer
gist.github.com
The Evolution of a Python Programmer
1–10 of 45 posts
Re: The Evolution of a Python Programmer
#2Re: The Evolution of a Python Programmer
#3 import operator as op
import functools as f
fact = lambda x: f.reduce(op.mul, range(1, x + 1))
print(fact(6))
If you're using Python 2.x, you can make it a bit shorter due to reduce being in the default namespace: import operator as op
fact = lambda x: reduce(op.mul, xrange(1, x + 1))
print fact(6)Re: The Evolution of a Python Programmer
#4Timeit's time for three functions:
Lazy Programmer - 0.907521744301
Lazier Programmer - 1.0473810545812512
Using math.factorial - 0.12187403971609001
Re: The Evolution of a Python Programmer
#5Re: The Evolution of a Python Programmer
#6 print reduce(lambda x, y: x*y, xrange(2, 6+1))
As a newish Python guy (5 months), I'm interested as to why the preferable solution seems to be to import operator and use the multiplication function? (I'm purposely ignoring the more preferable call to the C library)Re: The Evolution of a Python Programmer
#7Re: The Evolution of a Python Programmer
#8I prefer "short but to the point". This is instinctively what I threw in iPython before looking past first snippet: print reduce(lambda x, y: x*y, xrange(2, 6+1)) As a newish Python guy (5 months), I'm interested as to why the preferable solution seems to be to import operator and use the multiplication function? (I'm purposely ignoring the more preferable call to the C library)
1) The Python community doesn't really like lambdas. It's almost always considered better style to declare a named function, even if it's a short one-liner. If it's already available in the standard library, use that instead of re-implementing it as an unnecessary lambda.
2) This is an adaptation of jokes that have been made about many languages before Python, so the code isn't very Pythonic to start with. Most of the complex ones have errors that prevent them from running, they're just for comedic effect.
Re: The Evolution of a Python Programmer
#9So true...
Re: The Evolution of a Python Programmer
#10 from math import gamma
def factorial(x):
return gamma(x+1)
This has the advantage of working correctly for non-integer arguments.