[그 외]/ㄴ (코테연습 : 파이썬 ver)
[프로그래머스] 시저 암호 (파이썬)
__hyeon2__
2021. 6. 17. 17:38
728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/12926
코딩테스트 연습 - 시저 암호
어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다. 예를 들어 "AB"는 1만큼 밀면 "BC"가 되고, 3만큼 밀면 "DE"가 됩니다. "z"는 1만큼 밀
programmers.co.kr
<나의 풀이>
def solution(s, n):
answer = ''
for i in s:
index = ord(i)
# 공백인 경우
if index == 32 :
answer += ' '
# 대문자인 경우
elif (index > 64) and (index < 91) :
if (index + n) > 90 :
index -= 26
answer += chr(index+n)
# 소문자인 경우
elif (index > 96) and (index < 123) :
if (index + n) > 122 :
index -= 26
answer += chr(index+n)
return answer
<다른 사람의 풀이>
def caesar(s, n):
s = list(s)
for i in range(len(s)):
if s[i].isupper():
s[i]=chr((ord(s[i])-ord('A')+ n)%26+ord('A'))
elif s[i].islower():
s[i]=chr((ord(s[i])-ord('a')+ n)%26+ord('a'))
return "".join(s)
# 실행을 위한 테스트코드입니다.
print('s는 "a B z", n은 4인 경우: ' + caesar("a B z", 4))
# <배운점>
# => 대소문자구문을 내장함수로 사용한 점
# => 넘어가는 범위를 26의 나머지로 구했다는 점
728x90
반응형