Apply Sequence Of Functions To An Object In Python
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)
Answer
The solution is quite simple:
def mycomputation(num):
for instruction in instruction_set:
num = instruction_dict[instruction](num)
return num
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module