1

I have a text file with students scores from taking a test and I need to find each students highest score and then print each students highest score, in the order of highest to lowest.

My code is down below however I keep getting tuple index out of range.

classChoice = str(input('What class scores would you like to view; rat, wolf or polar bear '))
fileName = 'results/' + classChoice + ".txt"
# init a list where you store the results
results = []
# open the file with results in a "read" mode
with open(fileName, "r") as fileinput:
# for each line in file with results, do following
    for line in fileinput:
    # remove whitespaces at the end of the line and split the line by ":"
    items = line.strip().split(":")
    # store the result as a list of tuples
    results.append(tuple(items))

# first it sorts all the tuples in `results` tuple by the second item (score)
# for each result record in sorted results list do the following
for result_item in sorted(results, key=lambda x: x[1], reverse=True):
# print the result in the format of the scores in your file 
    print ("{}:{}".format(result_item[0], result_item[1]))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

0

You have at least one tuple that doesn't have 2 values. This means you have empty lines, or lines with no : character in them:

>>> 'student\n'.strip().split(':')
['student']
>>> len('student\n'.strip().split(':'))
1
>>> '\n'.strip().split(':')
['']
>>> '\n'.strip().split(':')[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Guard against this by testing for the : character, or the length of the resulting items list.

Testing for : is easy enough:

for line in fileinput:
    if not ':' in line:
        # not a valid line, empty or not a key-value pair
        continue
    items = line.strip().split(":")
    # store the result as a list of tuples
    results.append(tuple(items))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

I think maybe that's because you forgot to tab the lines of reading from the file. Try to tab lines 9-12.

That'll help you Short Description of the Scoping Rules?

Community
  • 1
  • 1
wa11a
  • 183
  • 1
  • 7