You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/ch7_recursion.ptx
+15-5Lines changed: 15 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -34,9 +34,10 @@
34
34
as <md>n \times (n-1)!</md>.
35
35
</p>
36
36
<p>
37
-
Here is a Python implementation of factorial using just one function:
37
+
<xrefref="factorial-python-function"text="type-global"/> is the Python implementation of the factorial function. It checks for negative numbers, defines the base case for 0! and 1!, and implements the recursive step.
Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method instead of as a function. When this is done, you need to create an instance of the class in order to call the method. Below, we create the class <c>MathTools</c> with a method <c>factorial</c>, and we call it from the <c>main</c> function.
<xrefref="factorial-python-class"text="type-global"/> is the Python implementation of the factorial function as a method within a class. It maintains the same logic as the previous function but is now encapsulated within a class structure.
See if you can spot the differences in the Java version below.
87
95
</p>
88
96
<p>
89
-
Here is the equivalent Java code:
97
+
<xrefref="factorial-java-class"text="type-global"/> is the Java implementation of the factorial function. It follows the same logic as the Python version but adapts to Java's syntax and type system.
Notice the key differences from Python: instead of <c>def factorial(n):</c>, Java uses <c>public static int factorial(int n)</c> which declares the method's visibility as <c>public</c>, that it belongs to the class rather than an instance (hence, <c>static</c>), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, and, of course, all code blocks use curly braces <c>{}</c> instead of indentation.
0 commit comments