I'm trying to write a general function for adding/multiplying terms in a sequence
I'm trying to write a function with 4 arguments in python
def sequence(operation, sta开发者_StackOverflowrt, 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
reduce(lambda a,b: a+b, map(square, range(2,11)))
def sequence(operation, start, n, term):
return reduce(operation, map(term, range(start, n+1)))
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:
>>> range(2,10)
[2,3,4,5,6,7,8,9]
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:
>>> map(square,range(2,11))
[4, 9, 16, 25, 36, 49, 64, 81, 100]
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:
>>> from operator import add
>>> reduce(add, [4, 9, 16, 25])
... is equivalent to:
>>> add( add( add(4, 9), 16), 25)
... and:
>>> reduce(add, [4, 9, 16, 25, 36, 49, 64, 81, 100])
... is equivalent to:
>>> add( add( add( add( add( add( add( add(4, 9), 16), 25), 36), 49), 64), 81), 100)
You can define sequence in one-liner using Python Built-in functions range
, reduce
and map
.
from operator import add,mul
def square(x): return x * x
def sequence(oper,m,n,func):
if oper not in (add,mul):
return None
return reduce(lambda a,b: oper(a,func(b)),
xrange(m,n+1),
0 if oper==add else 1)
print sequence(add, 3,4, square)
print sequence(mul,2,3,square)
print sequence('qq',10,110,square)
result
25
36
None
精彩评论