【问题标题】:Calling every possible combination of functions调用所有可能的函数组合
【发布时间】:2017-03-30 21:06:43
【问题描述】:

假设我有一堆函数,每个都标记为 doThing1、doThing2 等,直到 doThing10。我想调用这些函数的所有可能组合。不必调用每个函数,但是每个函数只能调用一次。如何在 python 中高效地实现这一点?

【问题讨论】:

  • “所有可能的组合”是什么意思?给我们一个例子,比如说,三个函数。另外,您真的是指组合吗?还是您的意思是排列
  • 我的意思是组合,顺序无所谓。可能的组合是 doThing1,doThing3,doThing2 但是另一种可能的组合 doThing1,doThing2 或只是 doThing1 等

标签: python algorithm permutation computer-science combinatorics


【解决方案1】:

使用itertools.permutations(iterable\[, r\]) 获取所有排列并将您的函数放在一个列表中。

这是一个例子:

import itertools

def doThing1():
    print "thing 1"

def doThing2():
    print "thing 2"

def doThing3():
    print "thing 3"

functions = [doThing1, doThing2, doThing3]

for func_list in itertools.permutations(functions):
    for func in func_list:
        func() 

这是它的输出:

$ python permutations.py 
thing 1
thing 2
thing 3
thing 1
thing 3
thing 2
thing 2
thing 1
thing 3
thing 2
thing 3
thing 1
thing 3
thing 1
thing 2
thing 3
thing 2
thing 1

【讨论】:

  • OP 要求组合,而不是排列。另外,他说并不是每次都必须调用每个函数,所以推测thing1, thing3 的组合是有效的。您需要进行 1 功能组合、2 功能组合和 3 功能组合。
猜你喜欢
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多