Pythonmatics

Solving mathematical problems with Python

Python-agorean


One of the most famous mathematical statements is the Pythagorean theorem, which asserts that for a right triangle with sides an and b and hypotenuse c, the relationship a2 + b2 = c2 holds. If the lengths of the sides are natural numbers, then the triple of values (a, b, c) is called a Pythagorean triple. The smallest Pythagorean triple is (3, 4, 5). Every Pythagorean triple can be multiplied by an integer constant factor to obtain a new Pythagorean triple. For example, (6, 8, 10) and (9, 12, 15) are also Pythagorean triples, derive from (3, 4, 5). A Pythagorean triple that cannot be obtained as a multiple of another Pythagorean triple is called a primitive Pythagorean triple.

When it comes to coding, finding primitive Pythagorean triples can be achieved with a brute force algorithm. As mentioned in other posts, a brute force algorithm doesn’t aim to be clever, but it is straightforward and concise.

It’s Python time

triples = []
for a in range(1,200):                                      # 0 < a < 200
   for b in range(a+1,200):                                 # a < b < 200
      for c in range(b+1,200):                              # b < c < 200 ==> a < b < c
         if a**2 + b**2 != c**2:                            # a^a + b^2 = c^2 ?
            continue
         if any(a/x == b/y == c/z for (x,y,z) in triples):  # a multiplication of a known triple?
            continue
         triples.append((a,b,c))                            # add the triple to the list
print(triples) 

Output

[(3, 4, 5), (5, 12, 13), (7, 24, 25), (8, 15, 17), (9, 40, 41), (11, 60, 61), (12, 35, 37), (13, 84, 85), (15, 112, 113), (16, 63, 65), (17, 144, 145), (19, 180, 181), (20, 21, 29), (20, 99, 101), (24, 143, 145), (28, 45, 53), (28, 195, 197), (33, 56, 65), (36, 77, 85), (39, 80, 89), (44, 117, 125), (48, 55, 73), (51, 140, 149), (52, 165, 173), (57, 176, 185), (60, 91, 109), (65, 72, 97), (85, 132, 157), (88, 105, 137), (95, 168, 193), (104, 153, 185), (119, 120, 169)]

First, the code goes over all the potential triples using three nested for loops, up to a given value, for example, 200. Notice the way the loop ranges are defined. It guarantees that a < b < c. For a triple to be identified as a primitive Pythagorean triple, it has to satisfy a2 + b2 = c2 and not be a multiplication of a previously found triple. This requirement demonstrates Python’s robust and flexible syntax, utilizing the “any” operator and list comprehension effectively.

Another interesting Python syntax is the usage of the equality (==) operator with more than two variables.

.


One response to “Python-agorean”

Discover more from Pythonmatics

Subscribe now to keep reading and get access to the full archive.

Continue reading