Topic
12-ElectiveCourse-HUAWEI-CodingInterview
Key Point & Tag
Difficulty Assessment: Medium
Proficiency in Data Structure, System Design
Code
class ElectiveCourse:
# Input Part
def GetInput(self)->None:
'''
Get Input Data
'''
arr1 = list(map(str, input().strip().split(';'))) # ';' as separator
arr2 = list(map(str, input().strip().split(';'))) # ['01202021,75', ]
# Preprocess: transfrom data into {sid:score,...}
self.arr1 = {}
for s in arr1:
sid, score = s.split(',')
self.arr1[sid] = int(score)
self.arr2 = {}
for s in arr2:
sid, score = s.split(',')
self.arr2[sid] = int(score)
# Algorithm Part
def Solution(self)->int:
'''
Algorithm Solving Problem
'''
# Get data from self
arr1, arr2 = self.arr1, self.arr2
comm = [] # [{'sid':, 'tScore':},...]
for sid in arr1:
if sid in arr2:
# comm[sid] = arr1[sid] + arr2[sid]
comm.append({'sid': sid, 'tScore': arr1[sid] + arr2[sid]})
if not comm: # no stu join 2 courses meanwhile
return None
comm.sort(key = lambda x: [-x['tScore'], x['sid']]) # sort by [int(tScore) desc, str(sid) asc]
res = {} # {cid1:[sid1, sid2,...]},...}
for d in comm:
sid = d['sid']
cid = sid[:5]
# if not res.get(cid, None): # cid doesnt exist
# res[cid] = {}
res[cid] = res.get(cid, []) + [sid]
return dict(sorted(res.items()))
# Execution Part
if __name__ == "__main__":
# Instantiate
obj = ElectiveCourse()
# Get Input
obj.GetInput()
# Get Result
res = obj.Solution()
if not res:
print('NULL')
else:
for cid, sids in res.items():
print(cid) # class id
print(';'.join(sids))
```
# Test Cases01202021,75;01201033,95;01202008,80;01203006,90;01203088,100
01202008,70;01203088,85;01202111,80;01202021,75;01201100,88
Comments (0)


