尝试构建一段代码,该代码返回range(1,limit)中的数字是否为两个平方数(例如1**2 = 12**2 = 4的平方数)的总和,因此我尝试分配给一个数字,无论它们是那些平方数中任何一个的求和组合-例如1 + 1、1 + 4、4 + 16等)。下面是我写的内容,但是所有值都返回“ Not squared”,这是错误的。我认为代码可能有一个小问题,但是我对此很陌生,正在努力查看它的含义。如有任何指导,我将不胜感激。

码:

for n in range(1,21):
    lst = range(1,21)
    squares = [x**2 for x in lst]
    for i in range(1, 21):
        for x in range(1, 21):
            if i in squares:
                if x in squares:
                    n2 = i+x
    if n2 == n:
        print n, " - Sum of Squares"

    else:
        print n, " - Not a Sum of Squares"

最佳答案

当您将n与计算出的n2的最后一个值进行比较时,您应该

for n in range(1,21):
    lst = range(1,21)
    squares = [x**2 for x in lst]
    sum_of_squares = False
    for i in range(1, 21):
        for x in range(1, 21):
            if i in squares:
                if x in squares:
                    n2 = i+x
                    if n2 == n:
                        sum_of_square = True
    if sum_of_square:
        print n, " - Sum of Squares"
    else:
        print n, " - Not a Sum of Squares"

关于python - Python-平方和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14343736/

10-13 00:25