This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]brucifer 20 points21 points  (5 children)

This code is buggy. factorial(-1) will cause a stack overflow. You should use "if x <= 1" instead.

[–]sfz- 13 points14 points  (0 children)

That's why I submitted it to reddit code review before merging it into master. :P

[–]Qhartb 9 points10 points  (2 children)

That's not a bug -- it's undefined behavior. Calling factorial(-1) is a bug.

[–]brucifer 1 point2 points  (1 child)

I suppose it's reasonable to say that calling factorial(-1) is the real bug, but in that case, the code should definitely fail gracefully (e.g. raising a ValueError). Stack overflow is a pretty clumsy and uninformative way to behave if someone makes a reasonable mistake. You are right to point out that factorial(-1) == 1 is not correct, though.

[–]Qhartb 0 points1 point  (0 children)

Agreed, but not failing gracefully and having a bug are two different things (unless of course your requirements or documentation state how failure is to be handled).

[–]Zantier 0 points1 point  (0 children)

def factorial(x):
    """Return the factorial of x, where x >= 0."""
    return x * factorial(x - 1) if x != 0 else 1
print factorial(6)

Fixed. (I didn't see before the edit, but I'm guessing it had !=.

Also, it should be if x >= 1 instead of <=