A function is a first-class object in Python. One of the corollaries of this is that a function may return another function.
Your particular example can be written as follows:
def general_poly(A):
k = len(A)
def power(n):
return sum(j*n**(k-i) for i, j in enumerate(A, 1))
return power
res = general_poly([1, 2, 3, 4])(10) # 1234
The outer function general_poly
returns the inner function power
. The former takes a list, or an array, while the latter takes a scalar.
An alternative way of structuring your logic is to use functools.partial
. This creates a new function which one or more parameters fixed and obviates the need for an inner function.
from functools import partial
def general_poly(A, n):
k = len(A)
return sum(j*10**(k-i) for i, j in enumerate(A, 1))
genral_poly_10 = partial(general_poly, n=10)
res = genral_poly_10([1, 2, 3, 4]) # 1234
Of course, this is only useful if you wish to create a function for a specific power; trivially, n
can be used directly as an additional parameter without functools.partial
.
Note: Beware of mutable default arguments. So if your function has a mutable default argument, e.g. setting A=[]
in the above examples, the same list may be reused in an unforeseen way.