A Better Way Than Looping and Calling Functions That Loop and Call Another Functions

A better way than looping and calling functions that loop and call another functions

That method definitely sounds intensive since every bit of text will be gone over multiple times. O(n^3) complexity or something.

Instead, I would create a function to go through the input once and have it all parsed in one shot. To do that, it sounds like there's a handy pyparsing module you can use (I've never used it myself so I'm not sure of the learning curve, difficulty, or optimization). Otherwise, to do it manually, you'd have to keep track of your current "depth" (trans, group, or element) and determine if you're closing or opening a trans/group/element at that depth while keeping track of the data between opening and closing expressions. In short, don't find all "trans", just find where the first one begins, grab any unique data up until the next group begins, start the new group, grab unique data until the element begins, start the new element, grab data until it closes, see if there's another element or if the group closes, etc, etc. Not as concise, but certainly faster. If speed is not a concern, your method is fine. If it is (or will be) a concern, then you'll want to parse it in one pass.

Looping in function or multiple calling the function, what is faster?

Probably slightly faster with the loop inside the function, as there is a (slight) cost to each function call. However, it won't make much difference.

This is really premature optimization, and the root of all evil.

You should write it so it is clear, then if it's too slow, figure out where it's slow and optimize that.

Best practice to loop through an array of Functions with different signatures in Javascript?

After a lot of testing and benchmarking, the fastest method we've come up with is this (using @certainPerformance 's solution as a starting point):

  1. Store functions in an array of objects. This allows a user to insert new custom functions anywhere in the list (insert before 'taskA', etc.) and is much faster than an object of objects or Map.
  2. Call the tasks using array.some(). Somewhat faster than for of or for in, and even seemed slightly faster than array.map.
  3. Use function.call() to call the functions. This allows use of the this variable if you need to access other class features, for example. If you do this, you should also pass in this to array.some(), which preserves the this context without needing bind(this) which seemed quite slow.
  4. For parameters used by only a few functions, use an object params which gives a common function signature while allowing custom functions access to any relevant variables. For parameters common to all functions, pass in directly (for speed, especially if modifying that value).
//=== List of Pipeline Steps ===//
this.pipelineTasks = [
{ name: 'taskA', func: this.taskA },
{ name: 'taskB', func: this.taskB },
{ name: 'taskC', func: this.taskC }
];

// TaskA
TaskA(src, params) {
return src + params.title;
}

// TaskB
TaskB(src, params) {
return params.name ? params.name : params.name + "chicken";
}

// TaskC
TaskC(src, params) {
params.age = params.age + params.shoeSize;
return params.age > params.shoeSize ? params.age : params.shoeSize;
}

//=== Execute the processing pipeline ===//
processPipeline(src, name, age, shoeSize, title) {
const myParams = {
name : name,
age : 10,
shoeSize : 20,
title : title
};

while (myParams.age < 100) {
this.pipelineTasks.some(function(fn) {
return result = fn.func.call(this, src, myParams);
}, this));

//Alternatively, with arrow functions
// (slightly slower in Chrome, significantly slower in Node with hundreds
// of function calls, but doesn't require 'this' in array.some )
// this.pipelineTasks.some((fn) => result = fn.func.call(this, src, myParams));
}
}

Using a loop to call 'sequentially' named functions in C

You cannot have the compiler or runtime do this automatically in C, but you can manually list the function pointers and invoke them in a loop, i.e.:

// create your function prototype, which all functions must use
typedef void(*VoidFunc)(void);

// create the array of pointers to actual functions
VoidFunc functions[] = { foo_1, foo_2, foo_3 };

// iterate the array and invoke them one by one
int main(void)
{
for (int i = 0; i < sizeof(functions) / sizeof(*functions); i++)
{
VoidFunc fn = functions[i];
fn();
}

return 0;
}

Keep in mind that void func() is not the same as void func(void) in C.

Calling a function in a loop of another function

There are a couple of options here. If you have python 3.8+, you can use the walrus operator (:=) to put api_call directly in the condition of the loop:

def unpack_response():
while "meta" not in (api_response := api_call()):
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
return api_response

A more traditional, but no less idiomatic method is to run the loop forever and break when the correct condition is reached:

def unpack_response():
while True:
api_response = api_call()
if "meta" in api_response:
return api_response
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')

In both cases, you might consider slowing down the rate at which you make API calls with a sleep or similar.

How to call multiple functions using loop?

I would just pass the function as a parameter to the calculation function like so:

def method_1(new_parameters):
...

def method_2(new_parameters):
...

def calculation(parameters, method_name, method):
......
new_parameters = generate_new_params
method_call = method(**new_parameters)

if __name__ =="__main__":
......
output = calculation(parameters)

and then do your loop like this:

if __name__ =="__main__":
Methods = {"method-1": method_1, "method-2": method_2}
......
for key, value in Methods.items():
output = calculation(parameters, key, value)

How to call different functions in loop Python

try this:

if Pin.input(number of pin):
for i in range(0, 9):
globals()['for_'+str(i)]()

or

if Pin.input(number of pin):
for i in range(0, 9):
locals()['for_'+str(i)]()

Is it wise to call a method and nested loop in a foreach loop?

It's not a problem.

Do nested loops like this have performance implications? Is this good practice?

Nested loops have no specific performance implications.

But of course, a lot of data may be processed; depending on how much it is, you could reach memory or performance limits. But that is a given, and would also occur if you would use a different control structure instead of a nested loop.

An array-/foreach()-based solution will always require loading the full data set into memory before it starts processing.

If you are fetching data from a database, you could consider re-structuring your functions so they fetch and process a database record one by one instead of loading them all into an array, and foreaching over them. That allows you to process data sets that are larger than your script's memory limit.



Related Topics



Leave a reply



Submit