Search code examples
pythonlisttriplet

How to write a function "triplets" that takes in a number and returns a list of triplets?


Write a function triplets that takes a number n as argument and returns a list of triplets such that sum of first two elements of the triplet equals the third element using numbers below n. Please note that (a, b, c) and (b, a, c) represent same triplet.

triplets(5)

[(1, 1, 2), (1, 2, 3), (1, 3, 4), (2, 2, 4)]


Solution

  • You can do this with a list comprehension:

    def triplets(n): 
        return [ (a,c-a,c) for c in range(2,n) for a in range(1,c//2+1) ]