Programming Assignment Unit 4
Programming Assignment Unit 4
May 8, 2025
2
At the first stage, we define the hypotenuse function that takes two arguments, representing the
lengths of the two legs of a right triangle. We will then import the math module to utilize the
square root function for calculating the hypotenuse.
import math
# Calculate the hypotenuse based on the Pythagorean theorem: c^2 = a^2 + b^2
Output: 5.0
In this stage, we will add type annotations to the function parameters to indicate that they should
be numbers (either integers or floats). This helps code readability and future developers
understand the expected input types.
import math
# Additional tests
Output:
5.0
13.0
17.0
The final stage involves implementing input validation to ensure that the arguments are
import math
if a < 0 or b < 0:
Output:
5.0
13.0
17.0
try:
except ValueError as e:
print(f"Error: {e}")
Output:
In summary, the incremental development approach allowed us to build a robust and efficient
hypotenuse function by gradually adding features and addressing potential issues at each stage.
5
For the second part of this assignment, I will create a function to compute the factorial of a
The initial stage involves defining the factorial function. In this stage, I will create a simple
recursive implementation.
if n == 0:
return 1
# Recursive case
return n * factorial(n - 1)
Output: 120
Next, I will implement input validation to ensure that the input is a non-negative integer
6
if n < 0:
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(0)) # Output: 1
try:
except ValueError as e:
print(f"Error: {e}")
Output:
120
1
Error: Factorial is not defined for negative numbers.
7
In the final stage, I will replace the recursive approach with an iterative one for efficiency and to
support larger values of n without the risk of exceeding the maximum recursion depth.
if n < 0:
result = 1
result *= i
return result
Output:
120
720
3628800
479001600
8
In conclusion, the iterative approach to calculating the factorial not only avoids recursion depth
issues but also demonstrates a more efficient solution for larger input values. The incremental
development process ensured that each stage built upon the previous one, resulting in a reliable
Reference
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.
https://greenteapress.com/thinkpython2/thinkpython2.pdf