954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

finding the maximum and minimum

Write a program that can read the students records from the file “scores.dat”. This program will find the maximum and the minimum student scores. The first line in the file is a header. Each line (starting from the second line) contains the records of one student separated by spaces. These records are: the last name, the first, name, the ID, and the score.

# ETHAN PLYMALE

def main():
infile = open(scores.dat, 'r')

# Finding the maximum


and now I do not know what to do?

eplymale3043
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

# ETHAN PLYMALE

import string

def main():
infile = open(scores.dat, 'r')
infile.readline()

# Finding the maximum
for line in infile.readlines():
line = string.split(line)
score = line[3]
print score

i tried that but its not working.

eplymale3043
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

Please use code tags when posting code.

Are you receiving an error message? If so, please post it.

Initialize a maximum score variable (maxscore). Loop on the file object for line in file_obj: . Strip and split each line lineList = line.strip().split() . If the value of the score is greater thanmaxscore, update maxscore and save the line in another variable.

An alternative would be to read all the lines, each stripped and split, into a list and sort the list.

solsteel
Junior Poster
145 posts since Mar 2007
Reputation Points: 86
Solved Threads: 42
 

Please use code tags for your code.

You are getting close, but you need to find if the score is a new minimum or maximum each time through the loop. Something like this:

infile = open("test_scores.dat", "r")
mylist = infile.readlines()
infile.close()

# remove the header, first item in the list
del mylist[0]

max_score = 0
min_score = 100
for line in mylist:
    # split each line into a list at space/whitespace and unpack
    last_name, first_name, ID, score = line.split()
    # for testing only
    print last_name, first_name, ID, score
    # create integer scores
    if score.isdigit():
        score = int(score)
        # check if it is a new max
        if score > max_score:
            max_score = score
        # check if it is a new min
        elif score < min_score:
            min_score = score


Then just print out the max_score and min_score results.

Please study the code and the comments!

sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You