2

In the below mentioned code,my outer loop runs unnecessarily even if the condition is satisfied at the first iteration.I dont want to run the nested loop unnecessarily.How to reduce the nested loop complexity to increase the code performance?

 for i in List1:
   for j in sourceList:
     for k in List2:
      if (j[0]==i[1] and j[1]==k[1]):
       print (i[0],k[0])
2
  • 1
    Move that for loop to a function, and do a return. Commented Jul 11, 2019 at 5:34
  • Reduce time complexity? space complexity? Readability? Also do you want all i[0],k[0] matches, or just one. Also you say my outer loop runs unnecessarily even if the condition is satisfied at the first iteration but you have two outer loops here which one do you want to reduce the complexity off? Also giving examples of how all these lists look like, and expected output will also help Commented Jul 11, 2019 at 5:44

3 Answers 3

1

You can check the first condition if j[0] == i[1] before starting the innermost loop, and break on the first match.

for i in List1:
    for j in sourceList:
        #Check condition and only then run inner loop
        if j[0] == i[1]:
            for k in List2:
                #Break out of loop on first match
                if j[1] == k[1]:
                    print(i[0], k[0])
                    break
        else:
            continue
Sign up to request clarification or add additional context in comments.

Comments

1

Considering your goal is to print line by line i[0], k[0], you could use list comprehensions to reduce the complexity of a for loop as follows:

'\n'.join(f'{i[0]},{k[0]}' for i in List1 for j in sourceList if j[0]==i[1] for k in List2 if j[1]==k[1])

2 Comments

You forgot a for, also not sure how using a list comprehension reduces complexity? You still have 3 for loops
@DeveshKumarSingh, I updated my answer. I believe I have reduced a bit the complexity, but not as your answer since you are breaking the iterations as soon as you find the match.
0

You can do break:

for i in List1:
    for j in sourceList:
        for k in List2:
            if (j[0]==i[1] and j[1]==k[1]):
                print (i[0],k[0])
                break

Or use a def (function):

def f():
    for i in List1:
        for j in sourceList:
            for k in List2:
                if (j[0]==i[1] and j[1]==k[1]):
                    return (i[0],k[0])

1 Comment

I think that break will only do half the job: it will only exit the third for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.