Py学习  »  Python

用python编写n次函数

Garfield • 5 年前 • 1656 次点击  

我知道如何将两个函数作为输入来组合两个函数,并输出其组合函数,但如何返回组合函数 f(f(…f(x))) ? 谢谢

def compose2(f, g):
    return lambda x: f(g(x))

def f1(x):
    return x * 2
def f2(x):
    return x + 1

f1_and_f2 = compose2(f1, f2)
f1_and_f2(1)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49667
 
1656 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Mohideen bin Mohammed
Reply   •   1 楼
Mohideen bin Mohammed    5 年前

如果你想写一行字,

然后试试这个,

def f1(x):
    return x * 2
def f2(x):
    return x + 1

>>> out = lambda x, f=f1, f2=f2: f1(f2(x)) # a directly passing your input(1) with 2 function as an input (f1, f2) with default so you dont need to pass it as an arguments
>>> out(1)
4
>>> 

>>> def compose(f1, n):
...   def func(x):
...     while n:
...       x = f1(x)
...       n = n-1
...     return x
...   return func

>>> d = compose(f1, 2)
>>> d(2)
8
>>> d(1)
4
>>> 
Kent Shikama
Reply   •   2 楼
Kent Shikama    5 年前

注意这大部分是从 https://stackoverflow.com/a/16739439/2750819 但我想弄清楚你怎么能把它应用到任何一个函数n次。

def compose (*functions): 
    def inner(arg): 
        for f in reversed(functions): 
            arg = f(arg) 
        return arg 
    return inner

n = 10
def square (x): 
    return x ** 2

square_n = [square] * n
composed = compose(*square_n)
composed(2)

输出

179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
Mad Physicist
Reply   •   3 楼
Mad Physicist    5 年前

在嵌套函数中使用循环:

def compose(f, n):
    def fn(x):
        for _ in range(n):
            x = f(x)
        return x
    return fn

fn 将具有保留对 f n 你打电话来的 compose 和。