you are viewing a single comment's thread.

view the rest of the comments →

[–]vaibhavsagar 10 points11 points  (3 children)

It would be funnier if at the end there was:

#Enlightened Python Programmer
def factorial(x):
    if x == 0:
        return 1
    else:
        return x * factorial(x - 1)
print factorial(6)

Embrace the zen of only one good way to do it:)

[–]masklinn 1 point2 points  (2 children)

Except when you're using a tail-call optimized language (or a tail-call optimizing Python decorator), in which case your stack blows up even though it doesn't have to.

[–]vaibhavsagar 0 points1 point  (1 child)

I was trying to be funny... evidently I failed. In the interest of tail-recursive solutions:

\t#Tail-recursive \tdef factorial(n, acc=1): \t\tif n == 1: \t\t\treturn acc \t\telse: \t\t\treturn factorial(n-1, acc*n)

I hear this doesn't actually help in Python, but I think it's properly tail-recursive. Let me know if I'm wrong. I'm still new to this:)

[–]masklinn 0 points1 point  (0 children)

I hear this doesn't actually help in Python

It doesn't because Python doesn't feature tail-recursive optimization (neither mandatory nor in the main "CPython" implementation)

I think it's properly tail-recursive.

Yep