Blakester
Blakester

Reputation: 99

Unsure why my code is spitting out an empty set

new programmer here. So in the code I have below, the "year1" set works just like it is supposed to and spits out a set of years back at me. Although when I try to do the same thing for the "year2" set the only thing it spits back out at me is "set()".

I was wondering what is going on in the code that is making this so? Thanks for any help in advance!

def compare(word1, word2, startDate, endDate):
    with open('all_words.csv') as allWords:
        readWords = csv.reader(allWords, delimiter=',')
        year1 = set()
        for row in readWords:
            if int(startDate) <= int(row[1]) < int(endDate):
                if row[0] == word1:
                    year1.add(row[1])
        year2 = set()
        for row in readWords:
            if int(startDate) <= int(row[1]) < int(endDate):
                if row[0] == word2:
                    year2.add(row[1])

Upvotes: 0

Views: 61

Answers (2)

wwii
wwii

Reputation: 23773

As mentioned, you cannot iterate over the file twice without resetting it. You have duplicate code in your process - you could factor out the duplications and just iterate once.

def compare(word1, word2, startDate, endDate):
    with open('all_words.csv') as allWords:
        readWords = csv.reader(allWords, delimiter=',')
        year1 = set()
        year2 = set()
        for row in readWords:
            if int(startDate) <= int(row[1]) < int(endDate):
                if row[0] == word1:
                    year1.add(row[1])
                if row[0] == word2:
                    year2.add(row[1])

Upvotes: 1

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

At the point, you create year2 you have already read whole file (you are at the end of it). So you should seek() to the start of the file to go through it again. So:

....
allWords.seek(0)
year2 = set()
....

Upvotes: 2

Related Questions