자료구조, 알고리즘 문제 풀어보기(우주선 긴급 암호 해독)

|

개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.


문제 1: 우주선 긴급 암호 해독

테마/상황:

당신은 우주 탐사선 ‘노바-1’의 통신 장교입니다. 그런데 외계 신호의 공격으로 인해 동료들과의 통신 암호가 뒤죽박죽이 되어버렸습니다! 암호를 원래대로 복구하여 긴급 메시지를 해독해야 합니다. 암호는 단어의 순서가 거꾸로 뒤집혔고, 특정 글자가 다른 글자로 바뀌었습니다.

미션:

주어진 암호 문장을 해독하는 함수 decode_message를 작성하세요.

해독 규칙:

  1. 문장을 단어 단위로 분리한 후, 단어의 순서를 거꾸로 뒤집습니다.
  2. 각 단어에서 ‘!’는 ‘a’로, ‘@’는 ‘e’로, ‘#’는 ‘i’로, ‘$’는 ‘o’로, ‘%’는 ‘u’로 바꾸세요.
  3. 해독된 단어들을 다시 하나의 문장으로 합쳐 반환합니다.

예시:

  • 입력: "w@lc$m@! t$ pyth$n #s h@ll$!"
  • 출력: "hello is python to welcome"

<1. 내가 푼 풀이>

def decode_message(sentence):
    for i in sentence:
        if i == '@':
            sentence = sentence.replace('@', 'e')
        elif i == '#':
            sentence = sentence.replace('#', 'i')
        elif i == '$':
            sentence = sentence.replace('$', 'o')
        elif i == '%':
            sentence = sentence.replace('%', 'u')

    # sentence를 ,구분자로 나누고 []배열안에 넣기
    sentence = sentence.split()  
    # 역순으로 넣은 후 배열에서 스트링으로
    return ' '.join(sentence[::-1])  

decode_message("w@lc$m@! t$ pyth$n #s h@ll$!")

<2. 교육 내 답변>

def decode_message(encoded_str):
     # 1. 암호를 단어 단위로 분리합니다.
    words = encoded_str.split(' ')
    # 2. 단어의 순서를 거꾸로 뒤집습니다.
    words.reverse()

    decoded_words = []
    print(decoded_words)
    for word in words:
        # 3. 각 단어의 특수문자를 알파벳으로 바꿉니다.(메서드 체이닝 활용)
        temp_word = word.replace('@', 'e').replace('#', 'i').replace('$', 'o').replace('%', 'u')
        decoded_words.append(temp_word)

    # 4. 해독된 단어들을 다시 하나의 문장으로 합칩니다.
    return " ".join(decoded_words)

 # 예시 실행
encoded_message = "w@lc$m@! t$ pyth$n #s h@ll$!"
decoded_message = decode_message(encoded_message)
print(f"암호: {encoded_message}")
print(f"해독: {decoded_message}")