添加前20个数字的方块

时间:2017-10-16 22:31:52

标签: python python-3.x

这就是我所拥有的:

def add_squares(start, end):
   for n in range(start, end):
print(n**2 + n**2)

我想添加1-20

的数字方块

5 个答案:

答案 0 :(得分:2)

你可以试试这个:

def add_vals(start, stop):
    return sum(i**2 for i in range(start, stop))

print(add_vals(1, 21))

输出:

2870

答案 1 :(得分:1)

您必须将每个数字的正方形存储在某处。

def add_square(start, end):
    result = 0 
    for i in range(start, end+1):
        result += i**2
    print(result)

结果:2870

答案 2 :(得分:1)

仅仅是为了好奇,一种用于求和第n个数的平方的O(1)方法。

def sum_of_squares( n ):
    return n*(n+1)*(2*n+1)//6

来源:https://trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm

答案 3 :(得分:0)

确定存储在列表中:

sum_of_squares=[]

def add_squares(start, end,sum_of_squares):
   for n in range(start, end):
       calc=(n**2)
       sum_of_squares.append(calc)
       answer=sum(sum_of_squares)
   print(answer)

add_squares(1,21,sum_of_squares)

结果 2870

答案 4 :(得分:0)

这是我在Python中找不到的两个解决方案。

#list comprehension o(n)
def sum_of_squares1(start, end):
    return sum([n*n for n in range(start, end+1)])

#o(1) maths: Sum(s to e) = sum(1 to e) - sum(1 to (s-1))
def formula(n):
    return n*(n+1)*(2*n+1)/6

def sum_of_squares2(start, end):
    return formula(end)-formula(start-1)