Python - 正方形的总和

时间:2013-01-15 17:51:41

标签: python python-2.7

尝试构造一段代码,返回范围(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"

3 个答案:

答案 0 :(得分:2)

这不是最初的:::但它可能会给你更多的洞察力。

In [20]: from itertools import combinations_with_replacement

In [21]: nk=map(sum,(combinations_with_replacement([x**2 for x in range(1,21)],2)))

In [22]: for n in range(1,21):
    ...:     if n in nk:
    ...:         print n, " -Sum of Squares"
    ...:     else:
    ...:         print n, " -Not a sum of Squares"
    ...:         
1  -Not a sum of Squares
2  -Sum of Squares
3  -Not a sum of Squares
4  -Not a sum of Squares
5  -Sum of Squares
6  -Not a sum of Squares
7  -Not a sum of Squares
8  -Sum of Squares
9  -Not a sum of Squares
10  -Sum of Squares
11  -Not a sum of Squares
12  -Not a sum of Squares
13  -Sum of Squares
14  -Not a sum of Squares
15  -Not a sum of Squares
16  -Not a sum of Squares
17  -Sum of Squares
18  -Sum of Squares
19  -Not a sum of Squares
20  -Sum of Squares

In [23]: 

答案 1 :(得分:1)

你的意思是?

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"

输出:

>>> 
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
1  - Not a Sum of Squares
2  - Sum of Squares
2  - Not a Sum of Squares
...

答案 2 :(得分:0)

正如您所做的那样,将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"