알고리즘

[프로그래머스, 파이썬] 대충 만든 자판

hminor 2024. 3. 5. 09:55

풀이

  • keymap으로 받아오는 자판을 딕셔너리로 각 문자를 할당 후 
  • 해당 순서에 따른 인덱스값을 딕셔너리의 값으로 할당
  • 가장 적게 누르기를 원하기에 최소값을 넣어주기
  • 이후 targets에 해당하는 문자를 입력하여 cnt 변수에 누적합 적용
  • 만약 특정문자가 없는 경우 반복문 탈출하여 해결

 

def solution(keymap, targets):
    dic = dict()
    result = []
    for keys in keymap:
        for idx,key in enumerate(keys):
            if dic.get(key): dic[key] = min(dic.get(key),idx+1)
            else: dic[key] = idx+1
    for tg in targets:
        cnt = 0
        for i in tg:
            if dic.get(i): cnt += dic[i]
            else:
                cnt = 0
                break
        if cnt == 0: result.append(-1)
        else: result.append(cnt)
    return result