Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple nested for loop not working correctly

I can't see the problem here and it is driving me insane. I'm looping through 2 text files. Some lines in each file match and some don't. What I am doing is looping over file1. For each line in that file, loop over file2 and compare each element to see if they are the same. What's happening is my loop is stopping after the first loop through file1. Here is my code:

while f < 50:
    for line in file1:
        for name in file2:
            if name == line:
                print 'a match was found'
    f+=1

The while loop comes from somewhere else but it is working fine. I just included it for context. The problem is file1 only gives me the first line, compares it to all of the 'names' in file2 then stops instead of repeating the process for the next line in file1. Am I missing something glaringly obvious?

EDIT: If I put a print statement in after the first for loop and comment out the other for loop it loops through the whole first file

like image 928
adohertyd Avatar asked Jul 24 '12 16:07

adohertyd


People also ask

How do you fix a nested loop?

At the first step, the program encounters the outer loop and executes its first iteration. This first iteration triggers, as a reaction, the inner nested loop, which then runs to completion. Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop.

What is wrong about nested loop?

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

Why for loop is not working?

Remove the semicolon at the end of the first line. Then it will loop from 100 to 5. In case you want to end on zero then it should be i >=0; but I think you want it to stop at 5 which it is fine the way you have it.

Can nested loops cause performance issues?

Nested Loops can greatly reduce the innovative potential of the code because it negatively impacts performance.


1 Answers

You cannot loop through a file and then loop through the same file again without seeking to the start.

Either re-open file2, call .seek(0) on file2 or load all lines into a list and loop over that instead.

In your specific case, using a set for the names is probably going to be the fastest:

names = set(name.strip() for name in file2)
while f < 50:
    for line in file1:
        if line.strip() in names:
            f += 1

You can do the same with the lines in file1 and do a set intersection, provided that lines are unique in both file1 and file2.

like image 143
Martijn Pieters Avatar answered Oct 19 '22 20:10

Martijn Pieters