Pythagorean triplets using python's list comprehension

前端 未结 2 1274
我寻月下人不归
我寻月下人不归 2021-01-25 05:12

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         


        
相关标签:
2条回答
  • 2021-01-25 05:51

    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.

    0 讨论(0)
  • 2021-01-25 06:02

    Notice: This solution is only for the problem when a + b + c <= N

    Asssume that a<=b<=c, this version is a little faster:

    triplet = [(a,b,c) for a in range(1,N//3+1) for b in range(a,N//2+1) for c in range(b,N-1) if a**2 + b**2 == c**2]
    
    0 讨论(0)
提交回复
热议问题