-
위클리 챌린지 4주차 직업군 추천하기코딩 테스트/Level 1 2021. 8. 24. 10:17반응형
https://programmers.co.kr/learn/courses/30/lessons/84325
파이썬
def solution(table, languages, preference): jobs = {} for row in table: each = row.split() jobs[each[0]] = {each[1]: 5, each[2]: 4, each[3]: 3, each[4]: 2, each[5]: 1} result = {} for each in sorted(list(jobs)): result[each] = 0 for lang, pref in zip(languages, preference): if lang in jobs[each]: result[each] += pref * jobs[each][lang] return max(result.items(), key=lambda x: x[1])[0]
마지막 리턴문을 풀어서 보면 다음과 같다.
# result {'CONTENTS': 36, 'GAME': 25, 'HARDWARE': 41, 'PORTAL': 21, 'SI': 29} # result.items() dict_items([('CONTENTS', 36), ('GAME', 25), ('HARDWARE', 41), ('PORTAL', 21), ('SI', 29)]) # max(result.items(), key=lambda x: x[1])[0] HARDWARE
딕셔너리 컴프리헨션을 이용해 보자.
12줄을 4줄로 줄일 수 있다.def solution(table, languages, preference): jobs = {each[0]: {each[1]: 5, each[2]: 4, each[3]: 3, each[4]: 2, each[5]: 1} for each in map(lambda x: x.split(), table)} result = {each: sum(pref * jobs[each][lang] for lang, pref in zip(languages, preference) if lang in jobs[each]) for each in sorted(list(jobs))} return max(result.items(), key=lambda x: x[1])[0]
물론 더 줄일 수도 있다.
def solution(table, languages, preference): return max({each[0]: sum(pref * each[1][lang] for lang, pref in zip(languages, preference) if lang in each[1]) for each in sorted(list({each[0]: {each[1]: 5, each[2]: 4, each[3]: 3, each[4]: 2, each[5]: 1} for each in map(lambda x: x.split(), table)}.items()))}.items(), key=lambda x: x[1])[0]
golang
import "strings" func solution(table []string, languages []string, preference []int) string { tableMap := map[string]map[string]int{} for _, v := range table { temp := strings.Split(v, " ") tableMap[temp[0]] = map[string]int{temp[1]: 5, temp[2]: 4, temp[3]: 3, temp[4]: 2, temp[5]: 1} } result := map[string]int{} maxKey, maxVal := "", 0 for k, v := range tableMap { for i, lang := range languages { result[k] += v[lang] * preference[i] } if maxVal < result[k] { maxVal = result[k] maxKey = k } else if maxVal == result[k] && maxKey > k { maxKey = k } } return maxKey }
반응형