Ad

Apply Sequence Of Functions To An Object In Python

- 1 answer

Based on a set of instructions in the form of a string, I have to apply certain instructions (fxns) on an object, one after the other. This is a part of a larger system. I've arrived at this point. I need a way to iterate, and return the object's condition at the end of the instructions. I came across this reference, but over there, functions are being applied to a constant initial data to get a list of outputs. In my case however, the object is changing with the iteration. hence the while statement, but I also need an iterate to apply my ith function.

I tried to make a recursive function as well (it was inside a for statement, and it didn't feel right at all), with the base condition being length of instructions reaching 0, (each recursive call carrying out an instruction, till no more left, hence it is also decreasing in complexity), it looks like a good candidate for recursion, and I will appreciate a solution in that manner, if anyone is interested.

instruction_dict = {'D': lambda x : x/2 , 'M': lambda x: x%2, 'P':lambda x: x*2 , 'S': lambda x : x-2, 'A': lambda x : x+2}
instruction_set = 'PPPPPDDSAM'

def mycomputation (num):
    count, intermediate = 0, num
    fun_args = [instruction_dict[i] for i in instruction_set]

    while count <= len(fun_args):
        intermediate, count = fun_args(intermediate), count +1 #list is not callable, actually need fun_args[i](intermediate)
    return intermediate

fun_args is a list and a list is not callable, actually need something like - fun_args[i](intermediate)

Ad

Answer

The solution is quite simple:

def mycomputation(num):
    for instruction in instruction_set:
        num = instruction_dict[instruction](num)
    return num
Ad
source: stackoverflow.com
Ad