|
| 1 | +# Introduction |
| 2 | + |
| 3 | +The main challenge in solving the Pythagorean Triplet exercise is to come up with a 'fast enough' algorithm. |
| 4 | +The problem space can easily become very large, and 'naive' or more 'brute force' solutions may time out on the test runner. |
| 5 | + |
| 6 | +There are three reasonably common variations to this problem |
| 7 | +1. A [cubic time][approaches-cubic] solution, which uses highly nested loops and is non-performant. |
| 8 | +2. A [quadratic time][approaches-quadratic] solution, which uses one nested loop, and is reasonably easy to figure out. |
| 9 | +3. A [linear time][approaches-linear] solution, requiring some deeper understanding of the mathematics of finding trplets. |
| 10 | + |
| 11 | + |
| 12 | +If those terms are unclear to you, you might like to read about [time complexity][time-complexity], and how it is described by [asymptotic notation][asymptotic-notation]. |
| 13 | + |
| 14 | +The basic idea is to study how algorithms scale (_in CPU/GPU run time, memory usage, or other resource_) as the input parameters grow toward infinity. |
| 15 | +In this document we will focus on run time, which is critical for this exercise. |
| 16 | + |
| 17 | + |
| 18 | +## General guidance |
| 19 | + |
| 20 | +The goal of `Pythagorean Triplets` is to find combinations of three numbers `[a, b, c]` satisfying a set of conditions: |
| 21 | + |
| 22 | +1. `a < b < c` |
| 23 | +2. `a**2 + b**2 == c**2` (_otherwise known as the [Pythagorean theorem][Pythagorean-theorem]_) |
| 24 | +3. `a + b + c == n`, where `n` is supplied as a parameter to the function. |
| 25 | + |
| 26 | +For a given `n`, the solution should include all valid triplets as a list of lists. |
| 27 | + |
| 28 | + |
| 29 | +## Approach: Cubic time solution with 3-deep nested loops |
| 30 | + |
| 31 | +```python |
| 32 | +def triplets_with_sum(n): |
| 33 | + triplets = [] |
| 34 | + for a in range(1, n + 1): |
| 35 | + for b in range(a + 1, n + 1): |
| 36 | + for c in range(b + 1, n + 1): |
| 37 | + if a**2 + b**2 == c**2 and a + b + c == n: |
| 38 | + triplets.append([a, b, c]) |
| 39 | + return triplets |
| 40 | +``` |
| 41 | + |
| 42 | +This is the most 'naive' or 'brute force' approach, scanning through all possible integers `<= n` that satisfy `a < b < c`. |
| 43 | +This might be the first thing you think of when sketching out the algorithm on paper following the exercise instructions. |
| 44 | +It is useful to see the steps of the solution and to look at the size of the problem space. |
| 45 | + |
| 46 | +***Don't implement this in code!*** |
| 47 | + |
| 48 | +While it is a valid solution and it indeed works for small values of `n`, it becomes impossibly slow as `n` grows larger. |
| 49 | +For any truly large values of `n`, this code might take over all the available processing power on your local computer and never complete. |
| 50 | +For Exercism's online environment, the test suite will time out and fail. |
| 51 | + |
| 52 | + |
| 53 | +## Approach: Quadratic time solution with 2-deep nested loops |
| 54 | + |
| 55 | +```python |
| 56 | +def triplets_with_sum(n): |
| 57 | + triplets = [] |
| 58 | + for a in range(1, n + 1): |
| 59 | + for b in range(a + 1, n + 1): |
| 60 | + c = n - a - b |
| 61 | + if a ** 2 + b ** 2 == c ** 2: |
| 62 | + triplets.append([a, b, c]) |
| 63 | + return triplets |
| 64 | +``` |
| 65 | + |
| 66 | +Given the constraint that `a + b + c == n`, we can eliminate the innermost loop from the cubic approach and calculate `c` directly. |
| 67 | +This gives a substantial speed advantage, allowing the tests to run to completion in a reasonable time, _locally_. |
| 68 | + |
| 69 | +However, the Exercism online test runner will still time out with this solution. |
| 70 | + |
| 71 | +Examining the code, it is clear that the upper bounds on the `loop` variables are far too generous, and too much work is bing done. |
| 72 | + |
| 73 | + |
| 74 | +The solution below tightens the bounds and pre-calculates `c * c` in the outer `loop`. |
| 75 | +This gives about a 4-fold speedup, but still times out on the online test runner: |
| 76 | + |
| 77 | + |
| 78 | +```python |
| 79 | +def triplets_with_sum(n): |
| 80 | + result = [] |
| 81 | + for c in range(5, n - 1): |
| 82 | + c_sq = c * c |
| 83 | + for a in range(3, (n - c + 1) // 2): |
| 84 | + b = n - a - c |
| 85 | + if a < b < c and a * a + b * b == c_sq: |
| 86 | + result.append([a, b, c]) |
| 87 | + return result |
| 88 | +``` |
| 89 | + |
| 90 | +If a quadratic-time algorithm was the best available option, there are other ways to squeeze out small performance gains. |
| 91 | + |
| 92 | +For bigger problems outside Exercism, there are third-party packages such as [`numpy`][numpy] or [`numba`][numba] which replace Python |
| 93 | +loops (_versatile but relatively slow_) with routines written in C/C++, perhaps with use of the GPU. |
| 94 | +The runtime is still proportional to `n**2`, but the proportionality constant (_which would be measured in C/C++ as opposed to Python_) may be much smaller. |
| 95 | + |
| 96 | +Fortunately for the present discussion, mathematicians have been studying Pythagorean Triplets for centuries: see [Wikipedia][wiki-pythag], [Wolfram MathWorld][wolfram-pythag], or many other sources. |
| 97 | + |
| 98 | +So mathematically there are much faster algorithms, at the expense of reduced readability. |
| 99 | + |
| 100 | + |
| 101 | +## Linear time solutions |
| 102 | + |
| 103 | +```python |
| 104 | +from math import sqrt |
| 105 | + |
| 106 | +def triplets_with_sum(n): |
| 107 | + N = float(n) |
| 108 | + triplets = [] |
| 109 | + for c in range(int(N / 2) - 1, int((sqrt(2) - 1) * N), -1): |
| 110 | + D = sqrt(c ** 2 - N ** 2 + 2 * N * c) |
| 111 | + if D == int(D): |
| 112 | + triplets.append([int((N - c - D) / 2), int((N - c + D) / 2), c]) |
| 113 | + return triplets |
| 114 | +``` |
| 115 | + |
| 116 | +_All clear?_ 😉 |
| 117 | + |
| 118 | +After some thoughtful mathematical analysis, there is now only a single loop! |
| 119 | + |
| 120 | +Run time is now much faster, especially for large `n`, but a reasonable person could find it quite difficult to understand what the code is doing. |
| 121 | + |
| 122 | +If you do things like this out in the 'real world' ***please*** document your code carefully. |
| 123 | +It might also be helpful to choose variable names that are more descriptive to help readers understand all of the values and operations. |
| 124 | +In a few weeks, the bare code will puzzle your future self. |
| 125 | +People reading it for the first time are likely to struggle even more than you will. |
| 126 | + |
| 127 | +The code above uses fairly 'generic' programming syntax. |
| 128 | +Another submission used the same basic algorithm but in a more 'Pythonic' way: |
| 129 | + |
| 130 | + |
| 131 | +```python |
| 132 | +def triplets_with_sum(n): |
| 133 | + def calculate_medium(small): |
| 134 | + return (n ** 2 - 2 * n * small) / (2 * (n - small)) |
| 135 | + |
| 136 | + two_sides = ((int(medium), small) for small in range(3, n // 3) |
| 137 | + if small < (medium := calculate_medium(small)) |
| 138 | + and medium.is_integer()) |
| 139 | + |
| 140 | + return [[small, medium, (medium ** 2 + small ** 2) ** 0.5] |
| 141 | + for medium, small in two_sides] |
| 142 | +``` |
| 143 | + |
| 144 | +Although it is important to note that this solution could have chosen a better name for the `n` parameter, and clearer formatting for the `generator-expression` and the `list-comprehension`: |
| 145 | + |
| 146 | +```python |
| 147 | +def triplets_with_sum(number): |
| 148 | + def calculate_medium(small): |
| 149 | + |
| 150 | + # We have two numbers, but need the third. |
| 151 | + return (number ** 2 - 2 * number * small) / (2 * (number - small)) |
| 152 | + |
| 153 | + two_sides = ( |
| 154 | + (int(medium), small) for |
| 155 | + small in range(3, number // 3) if |
| 156 | + |
| 157 | + #Calls calculate_medium and assigns return value to variable medium |
| 158 | + small < (medium := calculate_medium(small)) and |
| 159 | + medium.is_integer() |
| 160 | + ) |
| 161 | + |
| 162 | + return [ |
| 163 | + [small, medium, (medium ** 2 + small ** 2) ** 0.5] |
| 164 | + for medium, small in two_sides |
| 165 | + ] |
| 166 | +``` |
| 167 | + |
| 168 | + |
| 169 | +## Which approach to use? |
| 170 | + |
| 171 | +If we could be sure that the code only had to handle small values of `n`, a quadratic method would have the advantage of clarity. |
| 172 | + |
| 173 | +However, the test suite goes up to 30_000, and the online test runner quickly times out. |
| 174 | +We therefor need to accept some less readable code and use a linear-time implementation. |
| 175 | + |
| 176 | +Full details of run-time benchmarking are given in the [Performance article][article-performance]. |
| 177 | + |
| 178 | +Overall, the results confirm the expectation that the linear-time methods are _very much_ faster. |
| 179 | +More surprisingly, the first example of the linear implementation (_with an explicit loop_) proved slightly faster than the more 'Pythonic' code. |
| 180 | +This is likely due to the overhead of creating and tracking the iterator for the `generator-expression`, calculating the 'expensive' `calculate_medium()` function call within that generator, and the additional 'expensive' conversions to `int()`. |
| 181 | + |
| 182 | +[Pythagorean-theorem]: https://en.wikipedia.org/wiki/Pythagorean_theorem |
| 183 | +[approaches-cubic]: https://exercism.org/tracks/python/exercises/pythagorean-triplet/approaches/cubic |
| 184 | +[approaches-linear]: https://exercism.org/tracks/python/exercises/pythagorean-triplet/approaches/linear |
| 185 | +[approaches-quadratic]: https://exercism.org/tracks/python/exercises/pythagorean-triplet/approaches/quadratic |
| 186 | +[article-performance]:https://exercism.org/tracks/python/exercises/pythagorean-triplet/articles/performance |
| 187 | +[asymptotic-notation]: https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation |
| 188 | +[numba]: https://numba.pydata.org/ |
| 189 | +[numpy]: https://numpy.org/ |
| 190 | +[time-complexity]: https://yourbasic.org/algorithms/time-complexity-explained/ |
| 191 | +[wiki-pythag]: https://en.wikipedia.org/wiki/Pythagorean_triple |
| 192 | +[wolfram-pythag]: https://mathworld.wolfram.com/PythagoreanTriple.html |
0 commit comments