Home > Blockchain >  Algorithm operation permutation in python: test different order of function execution
Algorithm operation permutation in python: test different order of function execution

Time:01-20

I have an algorithm that works like this (in pseudocode) :

def func_1(x):  
    apply processing 1 to x 
    return x
def func_2(x):
    apply processing 2 to  x
    return x
def func_3(x):
    apply processing 3 to  x
    return x

I would like to write a function func_all_processing(data, execution_order) that apply all these functions to some input data in a defined order and output the processed data, say:

func_all_processing(data, [1,2,3])

would do:

processed_data = func_1(data)
processed_data = func_2(processed_data)
processed_data = func_3(processed_data)
return processed_data

whereas

func_all_processing(data, [3,1,2])

would do:

processed_data = func_3(data)
processed_data = func_1(processed_data)
processed_data = func_2(processed_data)
return processed_data

What is the correct way to this?

CodePudding user response:

Put the functions in a list, and pass that list to func_all_processing(), which loops through them.

def func_all_processing(data, funcs):
    for f in funcs:
        data = f(data)
    return data

print(func_all_processing(data, [func_1, func_2, func_3]))

And if you want to test all different orders, use itertools.permutations() to loop through the different permutations.

CodePudding user response:

you could do:

def process_all(x,process_order:list):
    data = x
    for process in process_order:
        processed_date = globals()["func_{}".format(process.__str__())](data)
        data = processed_date
    return processed_date

CodePudding user response:

As indicated by @Bamar, I would use a list of functions and would encapsulate the functions within the func_all_processing function as follows:

def func_all_processing(data: [int, float], order: list) -> object:
    def func_1(x):  
        apply processing 1 to x 
        return x
    def func_2(x):
        apply processing 2 to  x
        return x
    def func_3(x):
        apply processing 3 to  x
        return x
    
    func_list = [func_1, func_2, func_2]
    rslt = data
    for i in order:
        rslt = func_list[i](rslt)
    return rslt    
  •  Tags:  
  • Related