Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping scores to People

Am trying to access a file that contain different people with their scores, so I need to calculate each total score add them and relate it to the respective person who scored those point. Then I need to sort the score and print in terminal who took what what position with respect to the point he scored. And the person with the least score took first followed by the second least and the person with the highest score took last. This code is not complte am stuck.

with open('golf.txt', 'r') as f:
    file = f.readlines()
    score = []
    name = []
    for i in file:
        i = i.split(':')
        name = i[0]
        score = i[1]

    list_score = []
    score = score.split(",")
    total_of_scores = 0
    for k in score:
        total_of_scores += k
        list_score.append(total_of_scores)
    print(list_score)
input ```
Bob Jones:4,6,3,3,4,3,5,5,4,4,3,3,2,3,4,3,4,4
Ted Smith:3,3,3,3,4,3,5,5,4,3,3,3,2,3,4,3,4,4
Taylor Martin:4,4,3,3,4,3,5,6,4,4,4,3,2,3,5,3,5,4

outout
FIRST:Ted Smith
SECOND:Adam Lee
THIRD:Mike Davis
LAST:Brian Foste

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

golf.txt:

Bob Jones:4,6,3,3,4,3,5,5,4,4,3,3,2,3,4,3,4,4
Ted Smith:3,3,3,3,4,3,5,5,4,3,3,3,2,3,4,3,4,4
Taylor Martin:4,4,3,3,4,3,5,6,4,4,4,3,2,3,5,3,5,4

Code:

with open('golf.txt', 'r') as f:
    file = f.readlines()
    scorecard=[]
    for i in file:
        name,scores=i.split(":")
        #print(name)
        score=0
        for i in scores.split(","):
            score+=int(i)
        scorecard.append([name,score])
    #print(scorecard)
    sorted_scorecard=sorted(scorecard,key=lambda x:x[1]) #sorted by the scores
    for name,score in sorted_scorecard:
        print(name)   #You can print score also to see the score

Output:

Ted Smith
Bob Jones
Taylor Martin
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading