0

I would appreciate any help with my homework assignment - It's a simple program for class that is supposed to check for a file, if it exists, it reads the file, and loads the data into the program, so you can list scores, and add more of them. Its supposed to keep only the top 5 scores.

Then when you close the program (by choosing option 0) it should write the top 5 scores to the scores.txt file. I think I got that to work properly, I'm just having trouble getting the program to read and populate the scores file correctly.

Here's my code so far:

scores = []

#Check to see if the file exists
try:
    file = open("scores.txt")
    for i in range(0, 5):
        name = file.readline()
        score = file.readline()
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]
    file.close()
except IOError:
    print "Sorry could not open file, please check path."


choice = None
while choice != "0":

    print    """
    High Scores 2.0

    0 - Quit
    1 - List Scores
    2 - Add a Score
    """


    choice = raw_input("Choice: ")
    print ""

    # exit
    if choice == "0":
        print "Good-bye."
        file = open("scores.txt", "w+")
        #I kinda sorta get this now... kinda...
        for entry in scores:
            score, name = entry
            file.write(name)
            file.write('\n')
            file.write(str(score))
            file.write('\n')
        file.close()

    # display high-score table
    elif choice == "1":
        print "High Scores\n" 
        print "NAME\tSCORE" 
        for entry in scores:
            score, name = entry    
            print name, "\t", score

    # add a score
    elif choice == "2":
        name = raw_input("What is the player's name?: ")
        score = int(raw_input("What score did the player get?: "))
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]     # keep only top 5 scores

    # some unknown choice
    else:
        print "Sorry, but", choice, "isn't a valid choice." 

raw_input("\n\nPress the enter key to exit.")
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
mandelbug
  • 1,548
  • 5
  • 20
  • 32
  • I've reformatted your post slightly - I would also leave out your edit for the time being - one thing at a time... – Jon Clements Nov 24 '12 at 17:56
  • 1
    It would be a lot easier if you wrote your file out in a CSV format instead of each field on different lines. – jdi Nov 24 '12 at 17:56
  • CSV format? What's that? – mandelbug Nov 24 '12 at 17:58
  • http://en.wikipedia.org/wiki/Comma-separated_values – jdi Nov 24 '12 at 17:59
  • Ok, I get what you are saying. I've just never heard that acronym. Even if I did that, how would I read the data without gathering the commas? This is my first time using external files in python. – mandelbug Nov 24 '12 at 18:01
  • 2
    Check out: http://docs.python.org/2/library/csv.html - are you sure you're using 2.3? That's a *very* outdated version of Python (2003 in fact) – Jon Clements Nov 24 '12 at 18:07
  • Scanning this I think you have a problem in that the sort if going to be based on text values. If you have 1, 10, 101 and 20 as scores but they are in the tuples as text then they will sort in that order and I think you want 1, 10, 20, 101. – PyNEwbie Nov 24 '12 at 18:13
  • @JonClements its for a class, Python 2.3.5, thats what they gave us. I would be using a newer version, but the teacher is teaching us the older version, and I don't want to get the syntax all mixed up when switching between versions. – mandelbug Nov 24 '12 at 18:27
  • 1
    @JoshI Wow - I'm seriously starting to wonder about the quality of some of these courses - the more I see on SO - the more I get discouraged :( – Jon Clements Nov 24 '12 at 18:28
  • @JonClements Yeah, I know what you mean. We are using a book thats almost 5 years old now. Its stupid. – mandelbug Nov 24 '12 at 22:06

1 Answers1

1

You should try writing your file in a Comma-Separated-Value (CSV). While the term uses the word "comma", the format really just means any type of consistent field separator, with each record on one line.

Python has a csv module to help with reading and writing this format. But I am going to ignore that and do it manually for your homework purposes.

Let's assume you have a file like this:

Bob,100
Jane,500
Jerry,10
Bill,5
James,5000
Sara,250

I am using comma's here.

f = open("scores.txt", "r")
scores = []
for line in f:
    line = line.strip()
    if not line:
        continue
    name, score = line.strip().split(",")
    scores.append((name.strip(), int(score.strip())))

print scores
"""
[('Bob', 100),
 ('Jane', 500),
 ('Jerry', 10),
 ('Bill', 5),
 ('James', 5000),
 ('Sara', 250)]
"""

You don't have to sort the list every time you read and append. You can do it once at the end:

scores.sort(reverse=True, key=lambda item: item[1])
top5 = scores[:5]

I realize lambda may be new to you. It is an anonymous function. We use it here to tell the sort function where to find the key for the comparisons. In this case we are saying for each item in the scores list, use the score field (index 1) for comparisons.

jdi
  • 90,542
  • 19
  • 167
  • 203
  • I had to rework it a little bit, but it worked. Mainly I just had to switch the `scores.append(name, score)` to `scores.append(score,name)`. It was reading them in backwards and I was confused. Ha. Thank you very much though. – mandelbug Nov 25 '12 at 02:41
  • Oh ok. Well if you store them in that order then you don't need the key lambda in the sort. It will just use the first index – jdi Nov 25 '12 at 02:46