Group Scores
Programming Interview
Medium
9 views
Problem Description
We have {x}. Create Player class and group by name summing scores. Output names sorted with total score.
Input Format
First line n. Next n lines: name score.
Output Format
Lines: name total.
Sample Test Case
Input:
5
A 3
B 5
A 2
C 10
B -1
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
class Player:
def __init__(self,name):
self.name=name
self.score=0
def add(self,x):
self.score+=x
mp={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
name=parts[0]
sc=int(parts[1])
if name not in mp:
mp[name]=Player(name)
mp[name].add(sc)
out=[]
for name in sorted(mp.keys()):
out.append(f'{name} {mp[name].score}')
print('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!