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

标签 python algorithm computer-science combinatorics

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

例子:

functionList = [function1, function2, function3]

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

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

最佳答案

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

关于python - 在每个可能的组合中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43150977/

相关文章:

python - 类型错误 : can only concatenate tuple (not "str") to tuple Error

java - 64 位无符号哈希函数

computer-science - 术语多路复用在计算机科学中是什么意思?

java - 字节数组是什么意思?

python - 直方图中矩形的最大面积 - 为什么我们需要堆栈?

python - 在 mechanize 中提交表单

python - 为什么 Python 的控制台在 Eclipse 中的调试视角中与 PyDev 分开?

python - 在 Python 中匹配和组合多个二维列表

c# - 交错放置一组电子邮件地址,避免具有相同域的项目连续

c++ - 整数的快速排序算法