Home > Back-end >  Is there a way to optimize these for loops?
Is there a way to optimize these for loops?

Time:10-13

There has to be a way to optimize this code in Python..

I have a function called calculate that needs to be run twice by a different dictionary (operators1 and operators2).

def main(string):
  for op1 in operators1:
    return calculate(string, op1)
    
  for op2 in operators2:
    return calculate(string, op2)

I simplified the code in this example a lot, but I have a bunch of other if-statements and for-loops in there, which is the exact same for both for-loops. So looking at that, I see a lot of duplicate lines. And I don't like duplicate lines, so I tried to optimize this as 1 for loop.

def main(string):
  for x in range(2):
    for op in operators (x 1):
      return calculate(string, op)

Unfortunately, operators (x 1) or something similar didn't work. It didn't actually add the 1 or 2 on there before looking at it as a variable for a dictionary.

Next thing I tried is putting both dictionaries in a new array opsArray

operatorsList = [operators1, operators2]

def main(string):
  for x in range(2):
    for op in operatorsList[x]:
      return calculate(string, op)

This didn't work either so now I'm clueless.

I'm just trying to combine the 2 for-loops in the first example into a single for-loops to avoid duplicate if-statements. Can someone tell me if what I'm trying to do here is actually possible and how it would be done?

CodePudding user response:

you where half way there, and so close to getting the answer.

operatorsList = [operators1, operators2]

def main(string):
  for elem in operatorslist:
    for op in elem:
      return calculate(string, op)

It just iterates through the dictionary and creates a dictionary elem of which is equal to operators1 and operators2

  • Related