삼각 암호 해독

PythonBeginner
지금 연습하기

소개

이 프로젝트에서는 문자를 직각 삼각형 형태로 배열하는 방법인 삼각형 암호를 해독하는 방법을 배우게 됩니다. 숨겨진 메시지는 각 행의 마지막 문자에 포함되어 있으며, 이 마지막 문자들을 연결하여 전송된 정보를 형성합니다.

👀 미리보기

text = " LcadcbsdxEsdxcx"
decryption_text = "LabEx"

🎯 과제

이 프로젝트에서 다음을 배우게 됩니다:

  • 삼각형 암호를 해독하는 함수를 만드는 방법
  • 빈 입력 또는 None 입력을 처리하는 방법
  • 각 행의 마지막 문자를 추출하고 연결하는 로직을 구현하는 방법

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있습니다:

  • 삼각형 암호의 개념 이해
  • 삼각형 암호를 해독하는 함수 구현
  • 빈 입력 또는 None 입력을 포함한 다양한 유형의 입력 처리
  • 문자열 조작에 대한 지식을 실제 문제 해결에 적용

삼각 암호 해독 함수 설정

암호화된 문자열 "LcadcbsdxEsdxcx"를 예로 들어 이해를 돕기 위해 제공된 예시는 직각 삼각형에 채워 넣으면 다음과 같습니다.

L
c a
d c b
s d x E
s d x c x

각 행의 마지막 문자를 추출하여 연결하면 해독된 메시지 "LabEx"를 얻을 수 있습니다.

이 단계에서는 triangle.py 파일에서 triangle_decryption() 함수를 만드는 방법을 배우게 됩니다.

  1. 코드 편집기에서 triangle.py 파일을 엽니다.
  2. 문자열 text를 입력으로 받아 해독된 텍스트를 문자열로 반환하는 triangle_decryption() 함수를 정의합니다.
def triangle_decryption(text: str) -> str:
    ## Initialize an empty string to store the decrypted text
    decryption_text = ""
✨ 솔루션 확인 및 연습

빈 입력 또는 None 값 처리

이 단계에서는 입력 text가 비어 있거나 None인 경우를 처리하는 방법을 배우게 됩니다.

  1. text가 비어 있지 않은지 확인하는 if 문을 추가합니다.
if text:
    ## Remove leading and trailing spaces from the text
    while text.startswith(" "):
        text = text[1:]
    while text.endswith(" "):
        text = text[:-1]

    ## Proceed with the decryption process
    ## ...
else:
    ## If the text is None, set the decrypted text to None
    decryption_text = None
✨ 솔루션 확인 및 연습

복호화 로직 구현

이 단계에서는 삼각형 암호를 해독하는 로직을 구현하는 방법을 배우게 됩니다.

  1. text 문자열의 현재 인덱스를 추적하기 위해 변수 i를 초기화합니다.
  2. 각 행의 단계 크기를 추적하기 위해 변수 step을 초기화합니다.
  3. while 루프를 사용하여 text 문자열을 반복하고 각 행의 마지막 문자를 decryption_text 문자열에 추가합니다.
i = 0
step = 1
while i < len(text):
    ## Append the current character to the decrypted text
    decryption_text += text[i]
    i = i + 1 + step
    step += 1

## Append the last character to the decrypted text if it is not the last character of the text
if i - step + 1 != len(text):
    decryption_text += text[-1]
✨ 솔루션 확인 및 연습

복호화된 텍스트 반환

이 마지막 단계에서는 해독된 텍스트를 반환하는 방법을 배우게 됩니다.

  1. 해독 프로세스 후, decryption_text 문자열을 반환합니다.
return decryption_text

완전한 triangle_decryption() 함수는 다음과 같아야 합니다.

def triangle_decryption(text: str) -> str:
    ## Initialize an empty string to store the decrypted text
    decryption_text = ""

    if text:
        ## Remove leading and trailing spaces from the text
        while text.startswith(" "):
            text = text[1:]
        while text.endswith(" "):
            text = text[:-1]

        i = 0
        step = 1
        while i < len(text):
            ## Append the current character to the decrypted text
            decryption_text += text[i]
            i = i + 1 + step
            step += 1

        ## Append the last character to the decrypted text if it is not the last character of the text
        if i - step + 1 != len(text):
            decryption_text += text[-1]

    else:
        ## If the text is None, set the decrypted text to None
        decryption_text = None

    return decryption_text

if __name__ == "__main__":
    print(triangle_decryption("LcadcbsdxEsdxcx"))
    print(triangle_decryption("Lcadb"))
    print(triangle_decryption(" LcadcbsdxEsdxcx"))
    print(triangle_decryption("L ab"))
    print(triangle_decryption(None))
✨ 솔루션 확인 및 연습

스크립트 테스트

이 단계에서는 제공된 예제를 사용하여 스크립트를 테스트하는 방법을 배우게 됩니다.

  1. triangle.py 파일을 저장합니다.
  2. 제공된 예제로 스크립트를 실행합니다:
python3 /home/labex/project/triangle.py

출력은 예상 결과와 일치해야 합니다:

## LcadcbsdxEsdxcx
LabEx
## Lcadb
Lab
## LcadcbsdxEsdxcx
LabEx
## L ab
Lab
## None
None

축하합니다! 프로젝트를 완료했습니다.

✨ 솔루션 확인 및 연습

요약

축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.