On Fri, Dec 31, 2021 at 9:42 AM hongy...@gmail.com
<hongyi.z...@gmail.com> wrote:
> > (Also, is this REALLY an optimization? Exception handling isn't the
> > fastest. Yes, it avoids some measure of recursion depth, but it looks
> > like a pretty inefficient way to do things. Python is not Lisp, and
> > there are very very few algorithms that actually benefit from tail
> > call optimization that wouldn't benefit far more from other ways of
> > doing the same thing.)
>
> Could you give some examples of the other methods you mentioned above?
>

If you have a function that has just a single tail call site, there's
usually no point writing it recursively.

def factorial(n):
    ret = 1
    for i in range(1, n + 1): ret *= i
    return ret

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Neither of these wants to be recursive, and writing them recursively
pollutes the function signature with parameters that really exist just
to be local variables. Passing an accumulator down is a terrible way
to demonstrate the beauty of recursion - it instead shows off how you
can shoehorn anything into recursion and make it worse in the process.

Please, everyone, stop trying to optimize the wrong things.

Write good code, don't try to make bad code stop crashing.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to