如何找到参数和功能的所有可能组合

时间:2019-08-17 09:52:09

标签: python combinations

信息和要求:

  1. 给出了两个列表,一个变量列表和一个函数列表,没有函数需要更多的参数,则变量列表中有变量。
  2. 必须为功能列表中的每个功能找到所有可能的输入变量组合。这意味着从0-> len(variables)
  3. 不能保证该函数将接受参数。
  4. 不能在功能列表中的功能上进行任何编辑,只能对其进行调用。

当我自己尝试解决此问题时,我发现了一个可以处理具有2个参数的函数的解决方案,但我不知道如何使其动态化,以便可以扩展到无限个参数

#  test input list
# functions = [test_method1, test_method2]
# variables = [1, 2, 3, 4, 5]

for f in functions: 
    for v in variables:  # loop all conditions
        try:  # checks if combination throws error
            f(v)
        except TypeError as a:  # if amount of parameters is > 1
            for v2 in variables:  # loop all conditions
                try:  # tries combination
                    f(v, v2)

                except TypeError as e:  

上面显示的代码不是解决方案的一部分,它只是我的最佳尝试,仅用于启发。

结果应该是所有函数都试图以所有可能的变量组合作为参数来运行。

1 个答案:

答案 0 :(得分:0)

您可以使用itertools获取所有子集并创建recursion function,如下所示:

from itertools import combinations

def test_method1(x):
    print("METHOD 1 :", x)

def test_method2(x, y):
    print("METHOD 2 :", x, y)

functions = [test_method1, test_method2]
variables = [1, 2, 3, 4, 5]

def run_all_methods(input_num):
    if input_num > len(variables):
        return
    for item in functions:
        try:
            for var_list in set(combinations(variables * input_num,input_num)):
                item(*list(var_list))
            input_num += 1
        except TypeError as a:
            run_all_methods(input_num+1)

run_all_methods(1)
OUT:
===
METHOD 1 : 2
METHOD 1 : 5
METHOD 1 : 3
METHOD 1 : 1
METHOD 1 : 4
METHOD 2 : 1 3
METHOD 2 : 2 1
METHOD 2 : 5 1
METHOD 2 : 2 5
METHOD 2 : 1 2
METHOD 2 : 3 3
METHOD 2 : 5 5
METHOD 2 : 4 4
METHOD 2 : 1 5
METHOD 2 : 2 2
METHOD 2 : 3 4
METHOD 2 : 4 1
METHOD 2 : 1 1
METHOD 2 : 3 2
METHOD 2 : 5 4
METHOD 2 : 4 5
METHOD 2 : 1 4
METHOD 2 : 2 3
METHOD 2 : 4 2
METHOD 2 : 3 5
METHOD 2 : 5 3
METHOD 2 : 3 1
METHOD 2 : 4 3
METHOD 2 : 5 2
METHOD 2 : 2 4

更新:

  1. combinations(variables,input_num)投射到set以避免重复。
  2. 您必须在input_num += 1之后添加for
  3.   

    *也可用于打开包装箱。它的原理类似于上面的“使用可变参量”。最简单的示例是,我们具有列表,元组或dict形式的数据,并且一个函数接受可变参数。

  4. variables * input_num可以使重复项exp:
a ==> [1, 2]
combinations(a, 2) => (1, 2)

a * 2 ==> [1, 2, 1, 2]
combinations(b, 2) => (1, 2)
                      (1, 1)
                      (1, 2)
                      (2, 1)
                      (2, 2)
                      (1, 2)

set(combinations(b, 2)) => (1, 2)
                           (1, 1)
                           (2, 1)
                           (2, 2)

阅读Understanding the asterisk(*) of Python

相关问题