在每个可能的组合中调用函数

Calling functions in every possible combination

我有一个函数列表。我想调用这些函数的每种可能组合,其中每个函数要么被调用一次,要么根本不被调用。他们的顺序并不重要。

示例:

functionList = [function1, function2, function3]

我想自己调用 function1() 以及 function1() + function2() 和 function1() + function2() + function3() 以及 function2() 等等

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

itertools 工作正常。但是你需要通过你想要使用的数字......在 1 和你的集合中的数字之间。不确定你是否需要 0 作为你的退化案例。以下作品。它可以被压缩,但它的可读性很好。查找 "python function pointer".

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

您可以使用 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