Re:The Python IAQ: Infrequently Answered Questions
by jules on Friday November 12, 2010 @01:18PM
(#1898563)
fact = lambda n: 1 if n <= 1 else n*fact(n-1)
or, for that matter: def fact(n): return 1 if n <= 1 else n*fact(n-1)
Re:The Python IAQ: Infrequently Answered Questions
by Goladus on Friday November 12, 2010 @03:49PM
(#1899221)
The point was to demonstrate that the one-liner fits easily as an argument to 'python -c' from the command-line. You could also point out "import _if;" probably won't let me call "_if()", but again that wasn't really the point.
Also, you'll need to know the version of python:
$ python
Python 2.4.3 (#1, Dec 11 2006, 11:39:03)
[GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fact = lambda n: 1 if n <= 1 else n*fact(n-1)
File "<stdin>", line 1
fact = lambda n: 1 if n <= 1 else n*fact(n-1)
^
SyntaxError: invalid syntax
>>>
When the code is primarily expressions, it's relatively easy to to this. Trying to do one-liners with regular python syntax can get tricky.
Also, if you have a series of similar relationships to present, it's often easier to line them up next to each other. You might cut 12 lines to 6 lines and the whole thing will be far clearer. Although in those cases, it's probably more effective to use a dictionary to achieve the same thing, with the advantage of data/logic separation.