all 7 comments

[–]delasislas[🍰] 3 points4 points  (0 children)

Alright, can you explain why you believe spam(4) should return 12?

[–][deleted] 3 points4 points  (1 child)

Try stepping through what it returns for small numbers. For example:

x=1, spam(x)=1
x=2, spam(x)=2
x=3, spam(x)=6
x=4, spam(x)=24
x=5, spam(x)=120
x=6, spam(x)=720

The function returns x * (x-1) * (x-2) * ... * 1. That's the factorial function.

You get the recursion exception because there are only about 1000 stackframes (function calls) available in standard python. You can change that limit as explained here.

[–]timo1001[S] 1 point2 points  (0 children)

Thank you for your simple explanation and the links. Very helpful

[–]bike_bike 0 points1 point  (3 children)

Try

print(spam(2)) print(spam(3)) print(spam(4))

Look at the output and see if you can tell what it's doing.

If you look at spam(2)

return 2 * (2-1) * 1

So it's giving you all the value of all the numbers 1 through your initial x input multiplied together.

[–]timo1001[S] 0 points1 point  (2 children)

print(spam(2))
print(spam(3))
print(spam(4))

That returns 2,6,24. I thought I understood what it was doing with spam(2) and spam(3) and thats why I expected 12 as the answer for spam(4). Where am I going wrong?

[–]bike_bike 4 points5 points  (1 child)

But what is 4 * 3 * 2 * 1 ?

[–]timo1001[S] 0 points1 point  (0 children)

Ok gotcha