Pythagorean triplets using python's list comprehension

半城伤御伤魂 提交于 2019-12-02 14:01:15

问题


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?


回答1:


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.




回答2:


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]


来源:https://stackoverflow.com/questions/46130443/pythagorean-triplets-using-pythons-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!