Complete the code to calculate factorial using recursion.
def factorial(n): if n == 0: return 1 else: return n * factorial(n[1]1)
The factorial function calls itself with n-1 to reduce the problem size until it reaches 0.
Complete the code to calculate factorial using iteration.
def factorial_iter(n): result = 1 for i in range(1, n[1]1): result *= i return result
The loop runs from 1 up to n inclusive, so we use n+1 in range.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
def fib(n): if n == 0 or n == 1: return n else: return fib(n[1]1) + fib(n[1]2)
Subtract 1 and 2 from n to move towards the base cases and stop recursion.
Fill both blanks to create a recursive function that sums numbers from 1 to n.
def sum_to_n(n): if n == 0: return 0 else: return n [1] sum_to_n(n [2] 1)
The function adds n to the sum of numbers up to n-1, reducing n each call.
Fill all three blanks to create a dictionary comprehension that maps numbers to their factorials using iteration.
def factorial_dict(n): return {i: [1] for i in range(1, n [2] 1)} def factorial_iter(num): result = 1 for j in range(1, num [3] 1): result *= j return result
The dictionary comprehension uses factorial_iter(i) for each i in range 1 to n+1. The loops use n+1 and num+1 to include n.
