![]() The recursion takes place when x is multiplied by the factorial of 1 less than x. "The way a recursion works is by building a stack of return values. What does this really mean? Again, I refer back to his teachings: ![]() What is happening here? As the moderator mtf so eloquently puts it, we effectively “build a return stack and solve the recursion by dumping the stack when a base case is reached”. In the body of the function, we have this line: return 1 if x < 2 else x * factorial(x-1) Let us then inspect why the proposed solution is not simply calling a built-in factorial function, but rather constructing a function that calculates factorials. Upon such noble intentions was the Python exercise in question established. Although there is indeed already an in-built Python function that can be used for this purpose, forcing us to think of our own function using our knowledge of factorial is a far better way to train us as new programmers. What this exercise aims for us to do is not to utilise the in-built factorial function, but rather, to understand how the calculation of factorial(n) works and then create a function to do this calculation. Upon trawling through multiple threads, I realised that this is in fact not the case. You face the same problem as me in that we both thought that our code (such as the one written above) is utilising the in-built Python factorial function, and is hence a bogus exercise. Return 1 if x < 2 else x * factorial(x-1) Let us first look at an example of the solution which this exercise is supposed to lead us to produce: def factorial(x): ![]() ![]() Hi for the late reply, I was a tad bit busy yesterday
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |