Python 在范围内()
Python for in range()
我正在使用 Python 做一个项目,我需要计算平方和,第一部分是:
"Function squares(initial,terms) has two parameters: the initial
integer number in the series and the number of terms in the series. It
will use repetition to compute the sum of the series, and then return
the results. For example, if the first parameter is 2 and the second
parameter is 4, the function will return 54. Sum = 2^2 + 3^2 + 4^2 + 5^2 =
54"
在问题的提示中它说要使用:
for in range()
我只是对如何在 python 中使用此功能以及如何实现它感到困惑。
您可以将范围映射为平方形式,然后求和。
首先,您的范围应该如下所示
l = range(initial,initial+terms)
然后,您可以使用函数映射此范围(我更喜欢使用 lambda 表达式)
m = map(lambda x: x**2, l)
最后,你可以得到这个结果的总和。
sum(m)
我想你想要的是
def sumSquares(a,b):
sum = 0
for n in range(a,a+b):
sum += n*n
return sum
编辑:误解了问题,因为第二个参数是限制。固定。
sum([i ** 2 for i in range(initial, initial + terms)])
或
sum(map(lambda x: x ** 2, range(initial, initial + terms)))
两者的工作方式相同。
def squaresum(a,b):
_sum = 0 # underline because sum is a function already
for x in range(a,b):
_sum += a**x
return _sum
我正在使用 Python 做一个项目,我需要计算平方和,第一部分是:
"Function squares(initial,terms) has two parameters: the initial integer number in the series and the number of terms in the series. It will use repetition to compute the sum of the series, and then return the results. For example, if the first parameter is 2 and the second parameter is 4, the function will return 54. Sum = 2^2 + 3^2 + 4^2 + 5^2 = 54"
在问题的提示中它说要使用:
for in range()
我只是对如何在 python 中使用此功能以及如何实现它感到困惑。
您可以将范围映射为平方形式,然后求和。
首先,您的范围应该如下所示
l = range(initial,initial+terms)
然后,您可以使用函数映射此范围(我更喜欢使用 lambda 表达式)
m = map(lambda x: x**2, l)
最后,你可以得到这个结果的总和。
sum(m)
我想你想要的是
def sumSquares(a,b):
sum = 0
for n in range(a,a+b):
sum += n*n
return sum
编辑:误解了问题,因为第二个参数是限制。固定。
sum([i ** 2 for i in range(initial, initial + terms)])
或
sum(map(lambda x: x ** 2, range(initial, initial + terms)))
两者的工作方式相同。
def squaresum(a,b):
_sum = 0 # underline because sum is a function already
for x in range(a,b):
_sum += a**x
return _sum