[英]How i do i change this code so it can deal with functions
The function below takes 3 parameters (f, a, and b). 下面的函数带有3个参数(f,a和b)。 Here f is a function and a and b are lower and upper bounds respectively, and f is the function to be summed over. 这里f是一个函数,a和b分别是下界和上限,并且f是要求和的函数。 #to calculate the sum of f from a to b #计算从a到b的f之和
def sum(f, a, b):
total = 0
for i in range(a, b+1):
total += f(i)
return total
Question 1. Type in the above code and calculate the sum of integers from 1 to 10, and 1 to 100 and 1 to 1000 问题1.键入上面的代码,并计算1到10、1到100以及1到1000的整数之和
Similar idea, but use *=
instead of +=
类似的想法,但使用*=
代替+=
def product(f, a, b):
total = 1
for i in range(a, b+1):
total *= f(i)
return total
For example 例如
def foo(x):
return x
>>> product(foo, 1, 5)
120
Just as adding 0 does nothing, multiplying by 1 does nothing. 就像加0一样,乘以1也一样。 Therefore, just use that as the start: 因此,仅以此作为开始:
def product(f, a, b):
total = 1
for i in range(a, b+1):
total *= f(i)
return total
Or use a functional style and you will come to success: 或使用功能样式,您将成功:
def product(f, a, b):
return reduce(lambda x, y: x*y, [f(n) for n in range(a, b+1)])
Run it going with function eg spam
: 运行它的功能,例如spam
:
def spam(x):
return x
print(product(spam, 1, 3))
>>>6
Edited: 编辑:
W/o f
param it will looks: W / O f
PARAM它将外观:
def product(a, b):
return reduce(lambda x, y: x*y, [n for n in range(a, b+1)])
print(product(1, 5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.