알고리즘
[알고리즘] 둘만의 암호
kimjaeyoon
2023. 3. 6. 18:23
Lv. 1
내 풀이
import string
def solution(s, skip, index):
answer = ''
for spell in s:
for i in range(index):
spell = string.ascii_lowercase[(string.ascii_lowercase.index(spell) + 1) %26]
if spell in skip:
spell = string.ascii_lowercase[(string.ascii_lowercase.index(spell) + 1) %26]
answer += spell
return answer
왜 안되는지 아직 이해 못함.
정답 풀이
from string import ascii_lowercase
def solution(s, skip, index):
result = ''
a_to_z = set(ascii_lowercase)
a_to_z -= set(skip)
a_to_z = sorted(a_to_z)
l = len(a_to_z)
dic_alpha = { alpha:idx for idx, alpha in enumerate(a_to_z) }
for i in s:
result += a_to_z[(dic_alpha[i] + index) % l]
return result
set 활용함.
dictionary 형태로 {알파벳:인덱스} 저장하여 접근.
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges