Search code examples
python-3.xlist-comprehensionpythagorean

Pythagorean triplets using python's list comprehension


I can find out Pythagorean triplets using for loop as follows:

def triplet(n): # Find all the Pythagorean triplets between 1 and n (inclusive)
  for a in range(n+1):
    for b in range(a):
      for c in range(b):
        if a*a == b*b + c*c:
          print(a, b, c)

I wanted to replace this with a one-liner using list comprehension and tried the following piece:

[a, b, c in range(n+1), range(a), range(b) if a*a == b*b + c*c]

But, I get a syntax error on the closing square bracket. I tried to change the list into tuple using simple brackets, but with no success. May I know how to get it right?


Solution

  • I think you mean

    [(a,b,c) for a in range(n+1) for b in range(a) for c in range(b) if a*a == b*b + c*c]
    

    That at least is syntactically valid.