├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── main.yml ├── .gitignore ├── 01_01 └── spiral_turtle.py ├── 02_01 └── while_loop_exit_conditions.py ├── 02_02 └── spiral_turtle.py ├── 02_03 └── factorial_iterative.py ├── 02_04 └── factorial_recursive.py ├── 02_05 ├── count_down.py └── factorial_recursive.py ├── 02_06 └── ch2_challenge.py ├── 02_07 └── solution.py ├── 03_01 └── fibonacci.py ├── 03_02 └── sum_list_recursive.py ├── 03_03 └── gcd.py ├── 04_01 └── multiply_recursive.py ├── 04_02 └── exponentiation.py ├── 04_03 └── str_len.py ├── 05_02 └── quicksort.py ├── 06_01 └── linked_list_recursive.py ├── 06_03 └── recursive_tree_traversal.py ├── 07_01 └── factorial_recursive.py ├── 07_02 └── memoization.py ├── 07_03 └── tail_recursion.py ├── 08_01 └── h_tree_fractal.py ├── 08_02 └── sierpinski_triangle.py ├── 09_02 ├── hanoi-turtle-demo-orig.py └── hanoi.py ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md └── trace_recursion.py /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) deotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Copy To Branches 2 | on: 3 | workflow_dispatch: 4 | jobs: 5 | copy-to-branches: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | fetch-depth: 0 11 | - name: Copy To Branches Action 12 | uses: planetoftheweb/copy-to-branches@v1 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *~ 3 | *.pyc 4 | 5 | -------------------------------------------------------------------------------- /01_01/spiral_turtle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import turtle 6 | 7 | MAX_LENGTH = 250 8 | INCREMENT = 10 9 | 10 | 11 | def draw_spiral(a_turtle, line_length): 12 | if line_length > MAX_LENGTH: 13 | return 14 | a_turtle.forward(line_length) 15 | a_turtle.right(90) 16 | draw_spiral(a_turtle, line_length + INCREMENT) 17 | 18 | 19 | charlie = turtle.Turtle(shape="turtle") 20 | charlie.pensize(5) 21 | charlie.color("red") 22 | draw_spiral(charlie, 10) 23 | turtle.done() 24 | -------------------------------------------------------------------------------- /02_01/while_loop_exit_conditions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | # No base case, no movement towards base case. 7 | # count = 1 8 | # while True: 9 | # print(count) 10 | 11 | # We have a base case, but no movement towards it. 12 | # count = 1 13 | # while True: 14 | # if count > 10: 15 | # break 16 | # print(count) 17 | 18 | # Base Case and movement towards it. 19 | count = 1 20 | while True: 21 | if count > 10: 22 | break 23 | print(count) 24 | count += 1 25 | -------------------------------------------------------------------------------- /02_02/spiral_turtle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | import turtle 7 | 8 | MAX_LENGTH = 250 9 | INCREMENT = 10 10 | 11 | 12 | def draw_spiral(a_turtle, line_length): 13 | if line_length > MAX_LENGTH: 14 | return 15 | a_turtle.forward(line_length) 16 | a_turtle.right(90) 17 | draw_spiral(a_turtle, line_length + INCREMENT) 18 | 19 | 20 | charlie = turtle.Turtle(shape="turtle") 21 | charlie.pensize(5) 22 | charlie.color("red") 23 | draw_spiral(charlie, 10) 24 | turtle.done() 25 | -------------------------------------------------------------------------------- /02_03/factorial_iterative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def factorial_iterative_while(n): # Condition-controlled version 8 | result = 1 9 | while n >= 1: 10 | result *= n 11 | n -= 1 12 | return result 13 | 14 | 15 | # Let's do some basic testing 16 | assert factorial_iterative_while(4) == 24 17 | assert factorial_iterative_while(6) == 720 18 | assert factorial_iterative_while(1) == 1 19 | assert factorial_iterative_while(0) == 1 20 | assert factorial_iterative_while(-7) == 1 21 | assert factorial_iterative_while(50) == 30414093201713378043612608166064768844377641568960512000000000000 22 | -------------------------------------------------------------------------------- /02_04/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def factorial(n): 8 | if n <= 1: 9 | # Base case 10 | return 1 11 | else: 12 | # Recursive case 13 | return n * factorial(n - 1) 14 | 15 | 16 | print(factorial(4)) 17 | print(factorial(6)) 18 | print(factorial(1)) 19 | print(factorial(0)) 20 | print(factorial(-7)) 21 | print(factorial(1000)) # RecursionError: maximum recursion depth exceeded in comparison 22 | -------------------------------------------------------------------------------- /02_05/count_down.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def count_down(n): 8 | print(n) 9 | if n == 0: 10 | # Base case 11 | print('Algorithm has hit the base case. Time to unwind.') 12 | return 13 | else: 14 | # Recursive case 15 | count_down(n - 1) 16 | print(n) 17 | return 18 | 19 | 20 | count_down(3) 21 | -------------------------------------------------------------------------------- /02_05/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import sys 6 | 7 | # Add parent directory to Python path. Use '..' for Windows. 8 | sys.path.insert(0, './') 9 | from trace_recursion import trace 10 | 11 | 12 | def factorial(n): 13 | if n <= 1: 14 | # Base case 15 | return 1 16 | else: 17 | # Recursive case 18 | return n * factorial(n - 1) 19 | 20 | 21 | factorial = trace(factorial) 22 | factorial(5) 23 | -------------------------------------------------------------------------------- /02_06/ch2_challenge.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import turtle 6 | 7 | MAX_LENGTH = 250 8 | INCREMENT = 10 9 | 10 | 11 | def draw_spiral(a_turtle, line_length): 12 | a_turtle.forward(line_length) 13 | a_turtle.right(90) 14 | draw_spiral(a_turtle, INCREMENT) 15 | 16 | 17 | charlie = turtle.Turtle(shape="turtle") 18 | charlie.pensize(5) 19 | charlie.color("red") 20 | draw_spiral(charlie, 10) 21 | turtle.done() 22 | -------------------------------------------------------------------------------- /02_07/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import turtle 6 | 7 | MAX_LENGTH = 250 8 | INCREMENT = 10 9 | 10 | 11 | def draw_spiral(a_turtle, line_length): 12 | if line_length > MAX_LENGTH: 13 | return 14 | a_turtle.forward(line_length) 15 | a_turtle.right(90) 16 | draw_spiral(a_turtle, line_length + INCREMENT) 17 | 18 | 19 | charlie = turtle.Turtle(shape="turtle") 20 | charlie.pensize(5) 21 | charlie.color("red") 22 | draw_spiral(charlie, 10) 23 | turtle.done() 24 | -------------------------------------------------------------------------------- /03_01/fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def fibonacci_iterative(n): 8 | a, b = 0, 1 9 | for i in range(n): 10 | a, b = b, a + b 11 | return a 12 | 13 | 14 | def fibonacci_recursive(n): 15 | if n < 2: 16 | return n 17 | return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) 18 | 19 | 20 | print(fibonacci_iterative(6)) 21 | print(fibonacci_recursive(6)) 22 | 23 | 24 | -------------------------------------------------------------------------------- /03_02/sum_list_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def list_sum(a_list): 8 | result = 0 9 | for val in a_list: 10 | result += val 11 | return result 12 | 13 | 14 | def list_sum_recursive(a_list): 15 | if len(a_list) == 0: 16 | return 0 17 | return a_list[0] + list_sum_recursive(a_list[1:]) 18 | 19 | 20 | assert list_sum([2, 3, 5, 7]) == 17 21 | assert list_sum([-4, -3, -2, -1, 10]) == 0 22 | 23 | assert list_sum_recursive([2, 3, 5, 7]) == 17 24 | assert list_sum_recursive([-4, -3, -2, -1, 10]) == 0 25 | assert list_sum_recursive([]) == 0 26 | assert list_sum_recursive([3]) == 3 27 | assert list_sum_recursive([-5, -3]) == -8 28 | -------------------------------------------------------------------------------- /03_03/gcd.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import sys 6 | 7 | # Add parent directory to Python path. Use '..' for Windows. 8 | sys.path.insert(0, './') 9 | from trace_recursion import trace 10 | 11 | 12 | def gcd_recursive(a, b): 13 | if b == 0: 14 | # Base case 15 | return a 16 | else: 17 | # Recursive case 18 | return gcd_recursive(b, a % b) 19 | 20 | 21 | gcd_recursive = trace(gcd_recursive) 22 | print(gcd_recursive(32, 12)) # From slides 23 | print(gcd_recursive(50, 15)) 24 | print(gcd_recursive(42, 28)) 25 | print(gcd_recursive(28, 42)) 26 | print(gcd_recursive(345, 766)) # Co-prime 27 | -------------------------------------------------------------------------------- /04_01/multiply_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def multiply_recursive(n, a): 8 | if n == 1: 9 | return a 10 | return multiply_recursive(n - 1, a) + a 11 | 12 | 13 | assert multiply_recursive(5, 4) == 20 # 5 is the multiplier, 4 is the multiplicand 14 | assert multiply_recursive(5, -4) == -20 # 5 is the multiplier, -4 is the multiplicand 15 | assert multiply_recursive(1, 4) == 4 # 1 is the multiplier, 4 is the multiplicand 16 | assert multiply_recursive(7, 8) == 56 # 7 is the multiplier, 8 is the multiplicand 17 | -------------------------------------------------------------------------------- /04_02/exponentiation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def exp_iterative(a, n): 8 | base = a 9 | for i in range(n - 1): 10 | a *= base 11 | return a 12 | 13 | 14 | def exp_recursive(a, n): 15 | if n == 1: 16 | return a 17 | else: 18 | return exp_recursive(a, n - 1) * a 19 | 20 | 21 | assert exp_iterative(5, 3) == 125 22 | assert exp_iterative(2, 4) == 16 23 | assert exp_iterative(1, 19) == 1 24 | assert exp_iterative(0, 2) == 0 25 | 26 | assert exp_recursive(5, 3) == 125 27 | assert exp_recursive(2, 4) == 16 28 | assert exp_recursive(1, 19) == 1 29 | assert exp_recursive(0, 2) == 0 30 | -------------------------------------------------------------------------------- /04_03/str_len.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | def iterative_str_len(a_str): 8 | result = 0 9 | for i in range(len(a_str)): 10 | result += 1 # result = result + 1 11 | return result 12 | 13 | 14 | def recursive_str_len(a_str): 15 | if a_str == "": 16 | return 0 17 | return recursive_str_len(a_str[1:]) + 1 18 | 19 | 20 | input_str = "I love recursion" 21 | print(len(input_str)) # Standard Pythonic way 22 | print(iterative_str_len(input_str)) 23 | print(recursive_str_len(input_str)) 24 | -------------------------------------------------------------------------------- /05_02/quicksort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import sys 6 | 7 | # Add parent directory to Python path. Use '..' for Windows. 8 | sys.path.insert(0, './') 9 | from trace_recursion import trace 10 | 11 | 12 | def quicksort(arr): 13 | if len(arr) <= 1: 14 | return arr 15 | pivot = arr[len(arr) // 2] 16 | left = [x for x in arr if x < pivot] 17 | middle = [x for x in arr if x == pivot] 18 | right = [x for x in arr if x > pivot] 19 | return quicksort(left) + middle + quicksort(right) 20 | 21 | 22 | def quicksort_verbose(arr): 23 | print(f"Calling quicksort on {arr}") 24 | if len(arr) <= 1: 25 | print(f"returning {arr}") 26 | return arr 27 | pivot = arr[len(arr) // 2] 28 | left = [x for x in arr if x < pivot] 29 | print(f"left: {left}; ", end="") 30 | middle = [x for x in arr if x == pivot] 31 | print(f"middle: {middle}; ", end="") 32 | right = [x for x in arr if x > pivot] 33 | print(f"right: {right}") 34 | to_return = quicksort_verbose(left) + middle + quicksort_verbose(right) 35 | print(f"returning: {to_return}") 36 | return to_return 37 | 38 | 39 | # data = [5, 2, 6, 1] 40 | # print(quicksort(data)) 41 | # print(quicksort_verbose(data)) 42 | 43 | # quicksort = trace(quicksort) 44 | # quicksort(data) 45 | # 46 | 47 | # What about data with duplicates? 48 | # data = [1, 6, 5, 5, 2, 6, 1] 49 | # print(quicksort(data)) 50 | 51 | # for challenge 52 | data = [5, 4, 3, 2, 1] 53 | print(quicksort_verbose(data)) -------------------------------------------------------------------------------- /06_01/linked_list_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | class Node: 8 | def __init__(self, data, next=None): 9 | self.data = data 10 | self.next = next 11 | 12 | 13 | def traverse(head): 14 | # Base case 15 | if head is None: 16 | return 17 | # Recursive case 18 | print(head.data) 19 | traverse(head.next) 20 | 21 | 22 | item1 = Node("dog") 23 | item2 = Node("cat") 24 | item3 = Node("rat") 25 | item1.next = item2 26 | item2.next = item3 27 | 28 | # traverse(item1) 29 | 30 | head = Node("dog", Node("cat", Node("rat", None))) 31 | traverse(head) 32 | -------------------------------------------------------------------------------- /06_03/recursive_tree_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | 7 | class Node: 8 | def __init__(self, data): 9 | self.data = data 10 | self.left = None 11 | self.right = None 12 | 13 | 14 | def preorder_print(root, path=""): 15 | """Root->Left->Right""" 16 | if root: 17 | path += str(root.data) + "-" 18 | path = preorder_print(root.left, path) 19 | path = preorder_print(root.right, path) 20 | return path 21 | 22 | 23 | def inorder_print(root, path=""): 24 | """Left->Root->Right""" 25 | if root: 26 | path = inorder_print(root.left, path) 27 | path += str(root.data) + "-" 28 | path = inorder_print(root.right, path) 29 | return path 30 | 31 | 32 | def postorder_print(root, path=""): 33 | """Left->Right->Root""" 34 | if root: 35 | path = postorder_print(root.left, path) 36 | path = postorder_print(root.right, path) 37 | path += str(root.data) + "-" 38 | return path 39 | 40 | 41 | if __name__ == '__main__': 42 | # Set up tree: 43 | root = Node("F") 44 | root.left = Node("D") 45 | root.left.left = Node("B") 46 | root.left.left.left = Node("A") 47 | root.left.left.right = Node("C") 48 | root.left.right = Node("E") 49 | root.right = Node("I") 50 | root.right.left = Node("G") 51 | root.right.left.right = Node("H") 52 | root.right.right = Node("J") 53 | 54 | print("Preorder:", preorder_print(root)) 55 | print("Inorder:", inorder_print(root)) 56 | print("Postorder", postorder_print(root)) 57 | 58 | r""" 59 | ______F______ 60 | / \ 61 | __D__ __I__ 62 | / \ / \ 63 | B E G J 64 | / \ \ 65 | A C H 66 | """ 67 | -------------------------------------------------------------------------------- /07_01/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | import sys 7 | 8 | 9 | def factorial(n): 10 | if n <= 1: 11 | # Base case 12 | return 1 13 | else: 14 | # Recursive case 15 | return n * factorial(n - 1) 16 | 17 | 18 | # print(sys.getrecursionlimit()) # 1000 is default 19 | # print(factorial(1000)) # RecursionError: maximum recursion depth exceeded in comparison 20 | sys.setrecursionlimit(1002) 21 | print(sys.getrecursionlimit()) 22 | print(factorial(1000)) 23 | -------------------------------------------------------------------------------- /07_02/memoization.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | import time 7 | from functools import lru_cache 8 | 9 | 10 | def fib(n): 11 | """ 12 | Returns the n-th Fibonacci number. 13 | """ 14 | if n == 0 or n == 1: 15 | return n 16 | return fib(n - 1) + fib(n - 2) 17 | 18 | 19 | @lru_cache 20 | def fib_lru(n): 21 | """ 22 | Returns the n-th Fibonacci number. 23 | """ 24 | if n == 0 or n == 1: 25 | return n 26 | return fib_lru(n - 1) + fib_lru(n - 2) 27 | 28 | 29 | # Manual caching using a dictionary. 30 | def fib_cache(n, cache=None): 31 | if cache is None: 32 | cache = {} 33 | if n in cache: 34 | return cache[n] 35 | if n == 0 or n == 1: 36 | return n 37 | result = fib_cache(n - 1, cache) + fib_cache(n - 2, cache) 38 | cache[n] = result 39 | return result 40 | 41 | 42 | n = 900 43 | 44 | # start = time.perf_counter() 45 | # fib(n) 46 | # end = time.perf_counter() 47 | # print("Plain recursive version. Seconds taken: {:.7f}".format(end - start)) 48 | # 49 | # start = time.perf_counter() 50 | # fib_lru(n) 51 | # end = time.perf_counter() 52 | # print("lru cache version. Seconds taken: {:.7f}".format(end - start)) 53 | # 54 | start = time.perf_counter() 55 | fib_cache(n) 56 | end = time.perf_counter() 57 | print("Manual cache version. Seconds taken: {:.7f}".format(end - start)) 58 | -------------------------------------------------------------------------------- /07_03/tail_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | import inspect 7 | 8 | 9 | def factorial(n): 10 | print("Non tail optimised stack size: ", len(inspect.stack(0))) 11 | if n == 0: 12 | return 1 13 | else: 14 | return factorial(n - 1) * n 15 | 16 | 17 | def tail_factorial_attempt(n, accumulator=1): 18 | print("Attempted tail optimised stack size: ", len(inspect.stack(0))) 19 | pass 20 | 21 | 22 | if __name__ == "__main__": 23 | print(factorial(5)) 24 | print(tail_factorial_attempt(5)) 25 | -------------------------------------------------------------------------------- /08_01/h_tree_fractal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import turtle 6 | 7 | SPEED = 5 8 | BG_COLOR = "blue" 9 | PEN_COLOR = "lightgreen" 10 | SCREEN_WIDTH = 800 11 | SCREEN_HEIGHT = 800 12 | DRAWING_WIDTH = 700 13 | DRAWING_HEIGHT = 700 14 | PEN_WIDTH = 5 15 | TITLE = "H-Tree Fractal with Python Turtle Graphics" 16 | FRACTAL_DEPTH = 2 17 | 18 | 19 | def draw_line(tur, pos1, pos2): 20 | # print("Drawing from", pos1, "to", pos2) # Uncomment for tracing the algorithm. 21 | tur.penup() 22 | tur.goto(pos1[0], pos1[1]) 23 | tur.pendown() 24 | tur.goto(pos2[0], pos2[1]) 25 | 26 | 27 | def recursive_draw(tur, x, y, width, height, count): 28 | draw_line( 29 | tur, 30 | [x + width * 0.25, y + height // 2], 31 | [x + width * 0.75, y + height // 2], 32 | ) 33 | draw_line( 34 | tur, 35 | [x + width * 0.25, y + (height * 0.5) // 2], 36 | [x + width * 0.25, y + (height * 1.5) // 2], 37 | ) 38 | draw_line( 39 | tur, 40 | [x + width * 0.75, y + (height * 0.5) // 2], 41 | [x + width * 0.75, y + (height * 1.5) // 2], 42 | ) 43 | 44 | if count <= 0: # The base case 45 | return 46 | else: # The recursive step 47 | count -= 1 48 | # Top left 49 | recursive_draw(tur, x, y, width // 2, height // 2, count) 50 | # Top right 51 | recursive_draw(tur, x + width // 2, y, width // 2, height // 2, count) 52 | # Bottom left 53 | recursive_draw(tur, x, y + width // 2, width // 2, height // 2, count) 54 | # Bottom right 55 | recursive_draw(tur, x + width // 2, y + width // 2, width // 2, height // 2, count) 56 | 57 | 58 | if __name__ == "__main__": 59 | # Screen setup 60 | screen = turtle.Screen() 61 | screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT) 62 | screen.title(TITLE) 63 | screen.bgcolor(BG_COLOR) 64 | 65 | # Turtle artist (pen) setup 66 | artist = turtle.Turtle() 67 | artist.hideturtle() 68 | artist.pensize(PEN_WIDTH) 69 | artist.color(PEN_COLOR) 70 | artist.speed(SPEED) 71 | 72 | # Initial call to recursive draw function 73 | recursive_draw(artist, - DRAWING_WIDTH / 2, - DRAWING_HEIGHT / 2, DRAWING_WIDTH, DRAWING_HEIGHT, FRACTAL_DEPTH) 74 | 75 | # Every Python Turtle program needs this (or an equivalent) to work correctly. 76 | turtle.done() 77 | -------------------------------------------------------------------------------- /08_02/sierpinski_triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | 6 | import turtle 7 | 8 | DEPTH = 2 9 | 10 | 11 | def draw_triangle(points, color, tur): 12 | tur.fillcolor(color) 13 | tur.up() 14 | tur.goto(points[0][0], points[0][1]) 15 | tur.down() 16 | tur.begin_fill() 17 | tur.goto(points[1][0], points[1][1]) 18 | tur.goto(points[2][0], points[2][1]) 19 | tur.goto(points[0][0], points[0][1]) 20 | tur.end_fill() 21 | 22 | 23 | def get_mid_point(p1, p2): 24 | return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) 25 | 26 | 27 | def sierpinski(points, depth, tur): 28 | draw_triangle(points, available_colours[depth], tur) 29 | if depth > 0: 30 | # From bottom left vertex 31 | sierpinski([points[0], 32 | get_mid_point(points[0], points[1]), 33 | get_mid_point(points[0], points[2])], 34 | depth - 1, tur) 35 | # From apex 36 | sierpinski([points[1], 37 | get_mid_point(points[0], points[1]), 38 | get_mid_point(points[1], points[2])], 39 | depth - 1, tur) 40 | # From bottom right vertex 41 | sierpinski([points[2], 42 | get_mid_point(points[2], points[1]), 43 | get_mid_point(points[0], points[2])], 44 | depth - 1, tur) 45 | 46 | 47 | if __name__ == '__main__': 48 | available_colours = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] 49 | my_turtle = turtle.Turtle() 50 | # my_turtle.hideturtle() 51 | my_turtle.color('white') 52 | my_turtle.shape('turtle') 53 | my_turtle.pensize(5) 54 | my_turtle.speed(1) # 1 is good for following along 55 | screen = turtle.Screen() 56 | screen.setup(600, 600) 57 | screen.title('Sierpinski Triangle') 58 | screen.bgcolor('black') 59 | vertices = [[-200, -100], [0, 200], [200, -100]] 60 | 61 | sierpinski(vertices, DEPTH, my_turtle) 62 | my_turtle.hideturtle() 63 | 64 | turtle.done() 65 | -------------------------------------------------------------------------------- /09_02/hanoi-turtle-demo-orig.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ turtle-example-suite: 3 | 4 | tdemo_minimal_hanoi.py 5 | 6 | A minimal 'Towers of Hanoi' animation: 7 | A tower of 6 discs is transferred from the 8 | left to the right peg. 9 | 10 | An imho quite elegant and concise 11 | implementation using a tower class, which 12 | is derived from the built-in type list. 13 | 14 | Discs are turtles with shape "square", but 15 | stretched to rectangles by shapesize() 16 | --------------------------------------- 17 | To exit press STOP button 18 | --------------------------------------- 19 | """ 20 | from turtle import * 21 | 22 | 23 | class Disc(Turtle): 24 | def __init__(self, n): 25 | Turtle.__init__(self, shape="square", visible=False) 26 | self.pu() 27 | self.shapesize(1.5, n * 1.5, 2) # square-->rectangle 28 | self.fillcolor(n / 6., 0, 1 - n / 6.) 29 | self.st() 30 | 31 | 32 | class Tower(list): 33 | "Hanoi tower, a subclass of built-in type list" 34 | 35 | def __init__(self, x): 36 | "create an empty tower. x is x-position of peg" 37 | self.x = x 38 | 39 | def push(self, d): 40 | d.setx(self.x) 41 | d.sety(-150 + 34 * len(self)) 42 | self.append(d) 43 | 44 | def pop(self): 45 | d = list.pop(self) 46 | d.sety(150) 47 | return d 48 | 49 | 50 | def hanoi(n, from_, with_, to_): 51 | if n > 0: 52 | hanoi(n - 1, from_, to_, with_) 53 | to_.push(from_.pop()) 54 | hanoi(n - 1, with_, from_, to_) 55 | 56 | 57 | def play(): 58 | onkey(None, "space") 59 | clear() 60 | try: 61 | hanoi(6, t1, t2, t3) 62 | write("press STOP button to exit", 63 | align="center", font=("Courier", 16, "bold")) 64 | except Terminator: 65 | pass # turtledemo user pressed STOP 66 | 67 | 68 | def main(): 69 | global t1, t2, t3 70 | ht(); 71 | penup(); 72 | goto(0, -225) # writer turtle 73 | t1 = Tower(-250) 74 | t2 = Tower(0) 75 | t3 = Tower(250) 76 | # make tower of 6 discs 77 | for i in range(6, 0, -1): 78 | t1.push(Disc(i)) 79 | # prepare spartanic user interface ;-) 80 | write("press spacebar to start game", 81 | align="center", font=("Courier", 16, "bold")) 82 | onkey(play, "space") 83 | listen() 84 | return "EVENTLOOP" 85 | 86 | 87 | if __name__ == "__main__": 88 | msg = main() 89 | print(msg) 90 | mainloop() 91 | -------------------------------------------------------------------------------- /09_02/hanoi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python Recursion Video Course 3 | Robin Andrews - https://compucademy.net/ 4 | """ 5 | import sys 6 | 7 | # Add parent directory to Python path. Use '..' for Windows. 8 | sys.path.insert(0, './') 9 | from trace_recursion import trace 10 | 11 | 12 | def towers_of_hanoi(n, source, destination, auxiliary): 13 | if n == 1: 14 | print("Move disk 1 from source", source, "to destination", destination) 15 | return 16 | towers_of_hanoi(n - 1, source, auxiliary, destination) 17 | print("Move disk", n, "from source", source, "to destination", destination) 18 | towers_of_hanoi(n - 1, auxiliary, destination, source) 19 | 20 | 21 | n = 3 22 | towers_of_hanoi = trace(towers_of_hanoi) 23 | # A, C, B are the names of the rods. 24 | # They correspond to source, destination, auxiliary 25 | towers_of_hanoi(n, 'A', 'C', 'B') 26 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2024 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | Please note, this project may automatically load third party code from external 8 | repositories (for example, NPM modules, Composer packages, or other dependencies). 9 | If so, such third party code may be subject to other license terms than as set 10 | forth above. In addition, such third party code may also depend on and load 11 | multiple tiers of dependencies. Please review the applicable licenses of the 12 | additional dependencies. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python: Recursion 2 | This is the repository for the LinkedIn Learning course Python: Recursion. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![Python: Recursion][lil-thumbnail-url] 5 | Recursion is part of the very fabric of computer science and software development, and whether you rarely use it or if it’s a key part of your development, there’s a good chance recursion is happening behind the scenes. Recursion is a powerful tool in breaking down complex problems into more manageable segments, and knowledge of recursion is a desirable trait that employers look for in developer positions. In this course, Robin Andrews takes a deep dive into the concepts, techniques, and applications of recursion using Python. He starts with some real-world examples of recursion, and then shows how it pertains to software development. He covers classic recursive algorithms like factorials and Fibonacci numbers, before showing how to write recursive algorithms in Python through practice exercises. After completing this course, you will have a better idea of how to use recursive algorithms to solve a wide range of software development issues. 6 | 7 | ## Instructions 8 | 9 | ### GitHub CodeSpaces 10 | 11 | Most of this course can be completed in a browser using GitHub CodeSpaces. There is a video near the start of the course explaining how to do this. 12 | 13 | ### Installing Python 14 | 15 | If you wish to work on your machine locally, you will need to install Python 3, available from [https://www.python.org/downloads/](https://www.python.org/downloads/) 16 | 17 | ### Branches 18 | 19 | > Please note: the solutions to many of the exercises in this course are available on the `main` branch, and it may be more convient to look for them there than switching to the end branch for each video. 20 | 21 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access. 22 | 23 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter. 24 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course. 25 | 26 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this: 27 | 28 | error: Your local changes to the following files would be overwritten by checkout: [files] 29 | Please commit your changes or stash them before you switch branches. 30 | Aborting 31 | 32 | To resolve this issue: 33 | 34 | Add changes to git using this command: git add . 35 | Commit changes using this command: git commit -m "some message" 36 | 37 | ### Instructor 38 | 39 | **Robin Andrews** 40 | 41 | _Founder of Compucademy_ 42 | 43 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/robin-andrews?u=104). 44 | 45 | We hope you enjoy this course on LinkedIn Learning. 46 | 47 | [lil-course-url]: https://www.linkedin.com/learning/python-recursion 48 | [lil-thumbnail-url]: https://cdn.lynda.com/course/2875238/2875238-1613499674834-16x9.jpg 49 | 50 | -------------------------------------------------------------------------------- /trace_recursion.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | 4 | def trace(func): 5 | # Store function name, for later use 6 | func_name = func.__name__ 7 | separator = '| ' # Used in trace display 8 | 9 | # Set the current recursion depth 10 | trace.recursion_depth = 0 11 | 12 | @wraps(func) 13 | def traced_func(*args, **kwargs): 14 | # Display function call details 15 | print(f'{separator * trace.recursion_depth}|-- {func_name}({", ".join(map(str, args))})') 16 | # Begin recursing 17 | trace.recursion_depth += 1 18 | result = func(*args, **kwargs) 19 | # Exit current level 20 | trace.recursion_depth -= 1 21 | # Display return value 22 | print(f'{separator * (trace.recursion_depth + 1)}|-- return {result}') 23 | 24 | return result 25 | 26 | return traced_func 27 | --------------------------------------------------------------------------------