Nathaniel Carlyon
Nathaniel Carlyon

Reputation: 11

Python Loop Only Iterating once with Large loop which takes input from a file

I'm doing this project and it needs to take input from names from the https://www.ssa.gov/oact/babynames/limits.html , so i created a loop to get all the names in the file and then made another to check for the largest name. However the loop only seems to run through once and gives the first name in the list. Is there a way to make it so it goes through the list?

    ## https://www.ssa.gov/oact/babynames/limits.html
file = open('yob2003.txt', 'r')
# variables to store the most popular name
# and the most popular name count
most_pop_name = ""
allNames = set()
count = 0

for line in file:  # loop to check for names
    list = line.split(',')
    if int(list[2]) > 100:  # not worth to work with stuff under 100
        allNames.add(list[0])
print(len(allNames))

bigList = sorted(allNames)

file.close()
file = open('yob2003.txt', 'r')
for x in range(len(bigList)):  # big loop that goes through once
    total = 0
    for line in file:
        list = line.split(',')
        if bigList[x] == list[0]:
            total += int(list[2])

    if total > count:
        most_pop_name = str(list[0])
        total = count

    #  print most popular name

print("Most popular name in [NJ] :: " + str(most_pop_name) + " " + str(count))

Upvotes: 0

Views: 52

Answers (1)

ashiswin
ashiswin

Reputation: 637

The issue with the loop is that you do for line in file. Every time you read a line from the file, it advances the read pointer within the file by a line. So the first time your big loop runs, it hits the inner loop and reaches the end of the file. Hence all subsequent iterations through big loop reach the inner loop, notice the file has reached the end, skips it and continues.

You are gonna want to reopen the file for each iteration of your big loop (move file = open('yob2003.txt', 'r') to after your for x in range(len(bigList)):.

Side note: Don't name your variable list as list refers to the Python data structure list(). This redefinition could cause confusions and bugs later on, so just beware.

Efficiency note: You open the file a lot and perform a lot of looping. It might be better to just execute everything in the first loop using a dictionary. For example:

import collections

file = open('yob2003.txt', 'r')
most_pop_name = ""
max_count = 0
counts = collections.defaultdict(int)

for line in file:
    arr = line.split(',')
    if int(arr[2]) < 100: continue

    counts[arr[0]] += int(arr[2])
    if counts[arr[0]] > max_count:
        max_count = counts[arr[0]]
        most_pop_name = arr[0]

# Python 2
print("Most popular name in [NJ] :: " + most_pop_name + " " + str(max_count))
# Python < 3.6
print("Most popular name in [NJ] ::", most_pop_name, max_count)
# Python >= 3.6
print(f"Most popular name in [NJ] :: {most_pop_name} {max_count}")

Upvotes: 1

Related Questions