Questions
Conceptual
Which of the following are required in a recursive function that does not infinitely recur?
A base case without a recursive function call
Recursive case that progresses toward the base case
Arguments changing in the recursive case
All of the above
SHOW SOLUTIONS
- All of the above
Code Writing
- Write a recursive function named
sumthat has anintparameternumberand returns anintthat is the sum of all nonnegative integers up to and includingnumber(1 + 2 + ... + number). For example,sum(number=4)should evaluate to1 + 2 + 3 + 4 = 10. If a negative argument fornumberis given, just return-1(What case is this?). It may help to come up with your base case and recursive case before beginning to write any code.
SHOW SOLUTIONS
1. The negative argument case is an edge case. Note: There are many equivalent ways this function could be written.
1 def sum(number: int) -> int:
2 """Sum of all nonnegative integers up to and including number."""
3 if number < 0: # Edge case
4 return -1
5 elif number > 0: # Recursive case
6 return number + sum(number=number - 1)
7 else: # Base case
8 return 0