我正在尝试编写一个通用函数来在序列中添加/相乘项
我正在尝试在Python中编写一个带有4个参数的函数
def sequence(operation, start, n, term):
,其中操作是一个函数,开始是序列的开始编号,n是序列的最后一个数字,术语是操作序列中术语的函数。
例如,
>>> sequence(add, 2, 10, square)
将返回 2, 3, 4, ..., 10 的平方和,
假设:
def square(x):
return x * x
I'm trying to write a function with 4 arguments in python
def sequence(operation, start, n, term):
where operation is a function, start is the beginning number of the sequence, and n is th last number of the sequence, term is function that manipulates the terms in the sequence.
For example
>>> sequence(add, 2, 10, square)
would return the summation of the square of 2, 3, 4, ..., 10
given that:
def square(x):
return x * x
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python中的range函数是半开的,即。 range(start, stop) 返回从 start 到 stop-1 的整数列表。因此,例如:
因此,要解决您的问题,您需要 range(start, n+1)。
要将函数“term”应用于此范围内的每个整数,您可以使用内置函数映射,例如:
函数的最后部分需要内置函数reduce,该函数将一个函数、一个可迭代对象和一个可选函数作为其参数初始值(在本例中不需要)。
reduce 将给定函数应用于可迭代的前两个元素;然后,它将函数应用于第一次计算的结果和可迭代的第三个元素,依此类推。
因此,例如:
... 相当于:
... 并且:
... 相当于:
The range function in Python is half-open ie. range(start, stop) returns a list of integers from start to stop-1. So, for example:
Therefore, to solve your problem you would need range(start, n+1).
To apply the function "term" to each integer in this range you would use the built-in function map eg:
The final part of the function requires the built-in function reduce which takes as its arguments a function, an iterable and an optional initial value (which is not required in this instance).
reduce applies the given function to the first two elements of the iterable; it then applies the function to the result of the first calculation and the third element of the iterable and so on.
So, for example:
... is equivalent to:
... and:
... is equivalent to:
您可以使用 Python 内置函数
range< 单行定义序列/code>、
reduce
和map
。You can define sequence in one-liner using Python Built-in functions
range
,reduce
andmap
.结果
result