mardi 20 février 2018

Can if statements be variable?

Apologies for the title, I don't know the terminology for what I am trying to do.

I have a function that has a series of nested loops, that runs a huge amount of times. The loops have many conditions as to whether they continue, or start over.

Occasionally, this function is called such that it needs to meet certain conditions that are rare. However, to check for them, I need to add even more if statements into my code.

Here is an example of what I am talking about, some of the looping in my function:

while 1:

    for node in currset:

        for (sum1, weight1, l1, r1) in pathdict[(0, node)]:  
            if sum1 & sum != sum1 or r1 == left or r1 == right or l1 == left:
                continue

            if level < connectright:
                if l1 == right:
                    continue
            elif l1 != right:
                    continue

            for (sum2, weight2, l2, r2) in pathdict[(level, r1)]:
                if sum2&sum != sum2:
                    continue
                if l2 != left or l2 == right:
                    continue
                andsum = sum1&sum2

                if andsum != r1:
                    continue  

Now, what do I do if I have a special case where many of these conditions no longer apply? The way I see it now, I can either 1.)write an entirely new function, 2.)rewrite the entire block of code and put it after another if statement, 3.)add a series of even more conditions, or 4.)write a function that checks my conditions at a given step.

The first 2 options seem bulky but at least my code would go fast. The 3rd seems horrible because the code becomes hard to read, and it slows down. And the 4th, I am unsure but it seems like calling these functions so many times would slow down my loops.

So my question is, is there some way that I can write "conditional if statements", where depending on the variables passed to the function, I could do something like:

if variable_passed == thing#1:
     my_if_statement = (if level < connectright:  continue)
else:
     my_if_statement = (if level > connectright:  continue)

This way I could easily change my conditions at the start of the function, before I begin looping.

Aucun commentaire:

Enregistrer un commentaire