如何在python中创建许多函数的所有组合?

时间:2018-04-18 21:04:32

标签: python

所以我有

x = 3 

def first(x):
    return x+2

def second(x):
    return x/2

def third(x):
    return x*4

我想制作一系列功能,如:

首先 - >第二 - >第三

但所有功能组合: 像第一个 - >第二,第一 - >第三

每次获得每个组合的x值。

我不仅需要将它们相乘,而且还能够进行多种长度的多重组合。

这里只是固定数量的组合: How to multiply functions in python?

问候和感谢

1 个答案:

答案 0 :(得分:2)

首先是组合部分:

>>> functions = [first, second, third]
>>> from itertools import combinations, permutations
>>> for n in range(len(functions)):
...     for comb in combinations(functions, n + 1):
...         for perm in permutations(comb, len(comb)):
...             print('_'.join(f.__name__ for f in perm))
...             
first
second
third
first_second
second_first
first_third
third_first
second_third
third_second
first_second_third
first_third_second
second_first_third
second_third_first
third_first_second
third_second_first

接下来,撰写部分会从问题How to multiply functions in python?中窃取@Composable装饰器并使用它来组合每个排列的函数。

from operator import mul
from functools import reduce
for n in range(len(functions)):
    for comb in combinations(functions, n + 1):
        for perm in permutations(comb, len(comb)):
            func_name = '_'.join(f.__name__ for f in perm)
            func = reduce(mul, [Composable(f) for f in perm])
            d[func_name] = func

现在你有了一个函数命名空间(实际上是可调用类),demo:

>>> f = d['third_first_second']
>>> f(123)
254.0
>>> third(first(second(123)))
254.0
>>> ((123 / 2) + 2) * 4
254.0