0. Statement 🫡
This blog is about the basic way of thinking about recursive algorithms. I learned it from this site. 🧐
1. Start 🤠
- What’s the simplest possible input?
- Play around with examples and visualize!
- Relate hard cases to simpler cases.
- Generalize the pattern.
- Write code by combining recursive pattern with the base case.
2. Questions 🤔️
1. Write a function that takes two inputs n and m and outputs the number of unique paths from the top left corner to the bottom right corner of a n x m grid. Constraints you can only move down or right 1 unit at a time.
def grid_paths(n, m):
if n == 1 or m== 1:
return 1
else:
return grid_paths(n, m - 1) +grid_paths(n - 1, m)
2. Write a function that counts the number of ways you can partition n objects using parts up to m (assuming m > 0)
def count_partitions(n, m):
if n == 0:
return 1
elif m == 0 or n < 0:
return 0
else:
return count_partitions(n - m, m) + count_partitions(n, m - 1)
3. Test
def grid_paths(n, m):
if n == 1 or m== 1:
return 1
else:
return grid_paths(n, m - 1) +grid_paths(n - 1, m)
def count_partitions(n, m):
if n == 0:
return 1
elif m == 0 or n < 0:
return 0
else:
return count_partitions(n - m, m) + count_partitions(n, m - 1)
if __name__ == "__main__":
print(grid_paths(10, 3))
print(count_partitions(10, 5))