1 분 소요

플레이페어 암호

플레이페어 암호문제 의 플레이페어 암호 문제를 풀어보았다.
구현해야할 부분이 좀 많아서 귀찮았지만 크게 어려운 문제는 아닌것 같았다.
스택을 알고 리스트를 좀 잘 다룬다면 쉽게 풀수 있을 것 같다.

  • python 구현
message = list(input())
key = list(input())


# A 부터 Z 까지 J를 제외하고 사용 5*5 = 25
lst = list(map(chr, range(65, 91)))
lst.remove('J')


# row, column 확인용 매트릭스.
# 매트릭스 구현 없이도 풀수 있을 것 같기도하고..
matrix = [[0]*5 for i in range(5)]


# 받은 키 에서 중복되는 부분 삭제: set 사용해보려 했으나 순서가 망가짐..
# 좋은 방법있으면 추천 바랍니다.
for i in range(len(key)):
    for j in range(i+1, len(key)):
        if key[i] == key[j]:
            key[j] = -1

key = [i for i in key if i != -1]


# 키에 있는 알파벳 삭제 후 남은 것을 키와 함께 합치기
for i in key:
    lst.remove(i)

key = key + lst

# 매트릭스 구현
for i in range(len(key)):
    row = i // 5 
    col = i % 5
    matrix[row][col] = key[i]


# 메시지 암호화를 위한 부분.
new_message = []
while message:
    temp0 = message.pop(0)
    if len(message) == 0:
        new_message.append([temp0, 'X'])
        break

    temp1 = message.pop(0)

    if temp0 != temp1:
        new_message.append([temp0, temp1])
    
    elif temp0 == temp1 and temp0=='X':
        new_message.append(['X','Q'])
        message.insert(0, temp1)

    elif temp0 == temp1:
        new_message.append([temp0, 'X'])
        message.insert(0, temp1)


# 주어진 조건에 따른 메시지 암호화 구현.
return_message = []

for arr in new_message:
    temp0, temp1 = arr
    idx0 = key.index(temp0)
    idx1 = key.index(temp1)

    row0 = idx0 // 5
    col0 = idx0 % 5

    row1 = idx1 // 5
    col1 = idx1 % 5

    # 같은 행인 경우
    if row0 == row1:
        col0 = (col0 + 1) % 5 
        col1 = (col1 + 1) % 5

    # 같은 열인 경우
    elif col0 == col1:
        row0 = (row0 + 1) % 5 
        row1 = (row1 + 1) % 5
    
    # 둘다 아닌경우
    else:
        col0, col1 = col1, col0

    
    temp0 = matrix[row0][col0]
    temp1 = matrix[row1][col1]

    return_message += [temp0 + temp1]

print(''.join(return_message))

댓글남기기