Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Pythagorean Triplet in the Python Track

Published at Jul 13 2018 · 0 comments
Test suite


This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which,

a**2 + b**2 = c**2

For example,

3**2 + 4**2 = 9 + 16 = 25 = 5**2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.

Find the product a * b * c.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test pythagorean_triplet_test.py
  • Python 3.4+: pytest pythagorean_triplet_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest pythagorean_triplet_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/pythagorean-triplet directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.


Problem 9 at Project Euler http://projecteuler.net/problem=9

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import unittest

from pythagorean_triplet import triplets_with_sum

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0

class PythagoreanTripletTest(unittest.TestCase):
    def test_triplets_sum_12(self):
        expected = set([(3, 4, 5)])
        self.assertEqual(triplets_with_sum(12), expected)

    def test_triplets_sum_108(self):
        expected = set([(27, 36, 45)])
        self.assertEqual(triplets_with_sum(108), expected)

    def test_triplets_sum_1000(self):
        expected = set([(200, 375, 425)])
        self.assertEqual(triplets_with_sum(1000), expected)

    def test_no_triplet_exists(self):
        expected = set([])
        self.assertEqual(triplets_with_sum(1001), expected)

    def test_two_matching_triplets(self):
        expected = set([(9, 40, 41), (15, 36, 39)])
        self.assertEqual(triplets_with_sum(90), expected)

    def test_several_matching_triplets(self):
        expected = set([(40, 399, 401),
                        (56, 390, 394),
                        (105, 360, 375),
                        (120, 350, 370),
                        (140, 336, 364),
                        (168, 315, 357),
                        (210, 280, 350),
                        (240, 252, 348)])
        self.assertEqual(triplets_with_sum(840), expected)

    def test_triplets_for_large_numbers(self):
        expected = set([(1200, 14375, 14425),
                        (1875, 14000, 14125),
                        (5000, 12000, 13000),
                        (6000, 11250, 12750),
                        (7500, 10000, 12500)])
        self.assertEqual(triplets_with_sum(30000), expected)

if __name__ == '__main__':
from math import ceil, gcd, sqrt

def triplets_in_range(range_start, range_end):
    for limit in range(range_start, range_end, 4):
        for x, y, z in primitive_triplets(limit):
            a, b, c = (x, y, z)

            # yield multiples of primitive triplet
            while a < range_start:
                a, b, c = (a + x, b + y, c + z)
            while c < range_end:
                yield (a, b, c)
                a, b, c = (a + x, b + y, c + z)

def euclidian_coprimes(limit):
    """See Euclidean algorithm
    mn = limit // 2
    for n in range(1, int(ceil(sqrt(mn)))):
        if mn % n == 0:
            m = mn // n
            if (m - n) % 2 == 1 and gcd(m, n) == 1:
                yield m, n

def primitive_triplets(limit):
    """See Euclid's formula
    for m, n in euclidian_coprimes(limit):
        a = m ** 2 - n ** 2
        b = 2 * m * n
        c = m ** 2 + n ** 2
        yield sorted([a, b, c])

def triplets_with_sum(triplet_sum):
    return {
        for triplet in triplets_in_range(1, triplet_sum // 2)
        if sum(triplet) == triplet_sum

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?