毕达哥拉斯三胞胎使用python的列表理解 [英] Pythagorean triplets using python's list comprehension

查看:117
本文介绍了毕达哥拉斯三胞胎使用python的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用for循环找出毕达哥拉斯三胞胎:

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?

推荐答案

我想你的意思是

[(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.

这篇关于毕达哥拉斯三胞胎使用python的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆