1903. Department Statistics
写得还蛮顺的,唯一需要解决的是重复count的问题,把count friend的对象改成set,最后算length就好了。其实用 bool list 也可以。
class Solution:
"""
@param employees: information of the employees
@param friendships: the friendships of employees
@return: return the statistics
"""
def departmentStatistics(self, employees, friendships):
total, memo = collections.defaultdict(int), collections.defaultdict(int)
friend = collections.defaultdict(set) # 这里用set,避免同一个人算两次
for e in employees:
idx, name, dept = [x.strip() for x in e.split(",")]
memo[idx] = dept
total[dept] += 1
for f in friendships:
i, j = [x.strip() for x in f.split(",")]
if memo[i] != memo[j]:
friend[memo[i]].add(i)
friend[memo[j]].add(j)
res = []
for dept, p in total.items():
res.append("%s: %s of %s" % (dept, len(friend[dept]), p))
return res
Last updated
Was this helpful?