
def solution(name, yearning, photo):
namelst = set(name)
cnt = {}
for i in range(len(name)):
cnt[name[i]] = yearning[i]
ans = []
for item in photo:
score = 0
for p in item:
if p in namelst:
score += cnt[p]
else: pass
ans.append(score)
return ans
입력값의 크기가 작기 때문에 문제는 통과했지만, 이름 - yearning 딕셔너리를 생성하는 것이 비효율적인 것 같았음.
+) if p in namelst: 가 없었더니 딕셔너리에 없는 이름에 대한 valueerror 발생
def solution(name, yearning, photo):
score_map = dict(zip(name, yearning))
return [sum(score_map.get(p, 0) for p in item) for item in photo]
1. name - yearning 딕셔너리 생성
cnt = {}
for i in range(len(name)):
cnt[name[i]] = yearning[i]
를 다음과 같이 표현.
score_map = dict(zip(name, yearning))
zip👉 같은 인덱스끼리 묶어서 튜플로 만들어줌
2. 이름이 존재하면 해당되는 yearning을 결과에 더함
ans = []
for item in photo:
score = 0
for p in item:
if p in namelst:
score += cnt[p]
else: pass
ans.append(score)
를 다음과 같이 표현.
return [sum(score_map.get(p, 0) for p in item) for item in photo]
dict.get(key, default)-> key값이 없으면 default 값으로 처리됨