[SOLVED] Algorithm operation permutation in python: test different order of function execution

Issue

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?

Solution

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.

Answered By – Barmar

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.