【问题标题】:How to make all combinations of many functions in python?如何在python中进行许多函数的所有组合?
【发布时间】:2018-04-18 21:04:31
【问题描述】:

所以我有

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?

问候和感谢

【问题讨论】:

  • @wim 您标记为重复的答案中没有组合主题和不同大小的组合。
  • 好的,很公平。重新打开。

标签: python


【解决方案1】:

首先是组合部分:

>>> 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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2020-01-25
    • 2021-03-05
    • 2016-04-26
    相关资源
    最近更新 更多