Combination
- Algorithms course
- Beginner
- Lesson 51/80
- 4 min
Compute C(n, k) using factorial.
Print results
Now we add print_results(). It prints the power and combination results to the screen.
This function calls the power and combination functions from previous lessons and shows their results.
Result display
The combination function from the previous lesson is also called. Two results are printed one after the other.
This shows the power of cumulative code: functions you wrote are used in later lessons.
Practice Print results
Write print_results(). Print power(2,5) and combination(5,2) results. Print 32 and 10.
Starter code
def power(base, exp):
# Compute power
if exp == 0:
return 1
return base * power(base, exp - 1)
def combination(n, k):
# Compute combination
if k == 0 or k == n:
return 1
return combination(n - 1, k - 1) + combination(n - 1, k)
def print_results():
# Print resultsSample solution
def power(base, exp):
# Compute power
if exp == 0:
return 1
return base * power(base, exp - 1)
def combination(n, k):
# Compute combination
if k == 0 or k == n:
return 1
return combination(n - 1, k - 1) + combination(n - 1, k)
def print_results():
# Print results
print(power(2, 5))
print(combination(5, 2))
print_results()Expected output
32 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Call
The power function is called with ____.
The power function is called with (2, 5).
Explanation: (2, 5) is right.
2 Combination: match the terms
| Term | Meaning |
|---|---|
print_results |
|
power |
Power |
combination |
Combination |
print |
Output |
3 What does print_results do?
- Sorts
- Computes and prints Correct answer
- Defines array
- Traverses tree
Explanation: It computes and prints.