Advertisements
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 :
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