【问题标题】:Calling functions in every possible combination以各种可能的组合调用函数
【发布时间】:2023-03-22 14:50:01
【问题描述】:

我有一个函数列表。我想调用这些函数的每个可能的组合,其中每个函数要么被调用一次,要么根本不被调用。它们所处的顺序无关紧要。

例子:

functionList = [function1, function2, function3]

我想单独调用 function1() 以及 function1() + function2() 以及 function1() + function2() + function3() 和 function2() 等

我将如何在 python 中实现它?我想使用 itertools.combinations 但似乎我不能用它来解决我的问题。

【问题讨论】:

标签: python algorithm computer-science combinatorics


【解决方案1】:

itertools 工作正常。但是您需要遍历要使用的数字……介于 1 和您的集合中的数字之间。不确定您是否需要 0 作为退化案例。以下作品。它可以被压缩,但它的可读性很强。查找“python函数指针”。

import itertools as it

def f1():
    return 1

def f2():
    return 2

def f3():
    return 3

functionList = [f1, f2, f3]
fsets = set([])
for num in range(1, len(functionList)+1):
    for combo in it.combinations(functionList, num):
        fsets.add(combo)

for fc_combo in fsets:
  temp = 0
  for f in fc_combo:
      temp += f()
  print temp

【讨论】:

    【解决方案2】:

    您可以使用itertools recipe page中的powerset函数:

    from itertools import chain, combinations
    
    def powerset(iterable):
        """
        powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
        """
        xs = list(iterable)
        # note we return an iterator rather than a list
        return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))
    
    def f1():
        return "f1"
    
    def f2():
        return "f2"
    
    def f3():
        return "f3"
    
    functions = [f1, f2, f3]
    
    for function_comb in powerset(functions):
       out = ""
       if not function_comb:
          continue # skip the empty set of functions
       for f in function_comb:
          out += f()
       print out
    

    它产生以下输出:

    f1
    f2
    f3
    f1f2
    f1f3
    f2f3
    f1f2f3
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      相关资源
      最近更新 更多