Medium: Interview Core · Problem 43 of 82

Pythagorean Triples

MediumGenerators and IteratorsPython

A Pythagorean triple is three whole numbers a < b < c with a * a + b * b == c * c, such as (3, 4, 5).

Write pythagorean_triples(limit) that returns a list of all triples with c <= limit, as tuples, sorted by a and then by b. The tests include limit = 800, so a first version that tries every c may be too slow.

Understand the problem

Read comprehensions, then count the work.

What does [x * x for x in range(6) if x % 2 == 0] give? Type the list.

The comprehension takes each x from 0 to 5, keeps the even ones (0, 2, 4) and squares them. The if filters before the expression is evaluated.

A comprehension with three loops for a ... for b ... for c ... and limit = 1000. About how many combinations does it test?

  1. About a million
  2. About 170 million
  3. About a thousand

With a < b < c the number of combinations is about 1000 x 1000 x 1000 / 6 = 166 million. Each one needs a multiplication and a comparison. That takes many seconds in Python.

Write the brute force

Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.

def pythagorean_triples(limit):
    # Write the simple version here. It only has to be correct, not fast.
    pass
Hint 1: a question to ask yourself

How do you make sure a < b < c and avoid listing the same triple twice?

Hint 2: the shape of the answer

A list comprehension with three for parts: a from 1, b from a + 1, c from b + 1, up to the limit. Keep the combinations where a*a + b*b == c*c.

Find the bottleneck

Do you really need the third loop?

Once you know a and b, how many values of c can possibly work?

  1. Many
  2. At most one: the square root of a*a + b*b
  3. None

If c exists it must be exactly the square root of a*a + b*b. So instead of trying every c, calculate it and check that it is a whole number. That removes the innermost loop.

Which function gives the exact whole-number square root of an integer?

  1. n ** 0.5
  2. math.isqrt(n)
  3. round(n / 2)

math.isqrt returns the integer square root exactly. n ** 0.5 is a float and can be off by one for large numbers. Check with c * c == n.

Make it faster

Two loops and a square root.

def pythagorean_triples(limit):
    # Write the faster version here.
    pass
Hint 1: a question to ask yourself

Which loop can be replaced by a calculation?

Hint 2: the pattern

Loop over a and b. Compute c = isqrt(a*a + b*b). If c * c == a*a + b*b and c <= limit, you have a triple.

Hint 3: pseudocode

for a from 1 to limit: for b from a + 1 to limit: total = a*a + b*b c = isqrt(total) if c * c == total and c <= limit: add (a, b, c)

Reflect

Brute force: three loops

def pythagorean_triples(limit):
    return [(a, b, c)
            for a in range(1, limit + 1)
            for b in range(a + 1, limit + 1)
            for c in range(b + 1, limit + 1)
            if a * a + b * b == c * c]

Improved: calculate c

from math import isqrt

def pythagorean_triples(limit):
    triples = []
    for a in range(1, limit + 1):
        for b in range(a + 1, limit + 1):
            total = a * a + b * b
            c = isqrt(total)
            if c <= limit and c * c == total:
                triples.append((a, b, c))
    return triples

What this tests: nested comprehensions (several for parts), readable comprehension layout, math.isqrt, and noticing that a loop is a disguised calculation.

Reading a nested comprehension: the for parts read in the same order as nested loops, outermost first. [... for a in A for b in B] is the same as for a in A: for b in B:.

The improvement: the brute force searches for c; the faster version computes it. When one value is fully determined by the others, do not search for it.

Cost:

Version Time
Three loops O(n cubed)
Two loops and isqrt O(n squared)

What an interviewer might ask next: Generate all triples (also scaled ones such as 6, 8, 10) versus only primitive triples (no common divisor). How would you filter the primitive ones? (gcd(gcd(a, b), c) == 1.)