MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / encode

Function encode

ciphers/playfair_cipher.py:83–118  ·  view source on GitHub ↗

Encode the given plaintext using the Playfair cipher. Takes the plaintext and the key as input and returns the encoded string. >>> encode("Hello", "MONARCHY") 'CFSUPM' >>> encode("attack on the left flank", "EMERGENCY") 'DQZSBYFSDZFMFNLOHFDRSG' >>> encode("Sorry!", "SPE

(plaintext: str, key: str)

Source from the content-addressed store, hash-verified

81
82
83def encode(plaintext: str, key: str) -> str:
84 """
85 Encode the given plaintext using the Playfair cipher.
86 Takes the plaintext and the key as input and returns the encoded string.
87
88 >>> encode("Hello", "MONARCHY")
89 'CFSUPM'
90 >>> encode("attack on the left flank", "EMERGENCY")
91 'DQZSBYFSDZFMFNLOHFDRSG'
92 >>> encode("Sorry!", "SPECIAL")
93 'AVXETX'
94 >>> encode("Number 1", "NUMBER")
95 'UMBENF'
96 >>> encode("Photosynthesis!", "THE SUN")
97 'OEMHQHVCHESUKE'
98 """
99
100 table = generate_table(key)
101 plaintext = prepare_input(plaintext)
102 ciphertext = ""
103
104 for char1, char2 in chunker(plaintext, 2):
105 row1, col1 = divmod(table.index(char1), 5)
106 row2, col2 = divmod(table.index(char2), 5)
107
108 if row1 == row2:
109 ciphertext += table[row1 * 5 + (col1 + 1) % 5]
110 ciphertext += table[row2 * 5 + (col2 + 1) % 5]
111 elif col1 == col2:
112 ciphertext += table[((row1 + 1) % 5) * 5 + col1]
113 ciphertext += table[((row2 + 1) % 5) * 5 + col2]
114 else: # rectangle
115 ciphertext += table[row1 * 5 + col2]
116 ciphertext += table[row2 * 5 + col1]
117
118 return ciphertext
119
120
121def decode(ciphertext: str, key: str) -> str:

Callers 1

playfair_cipher.pyFile · 0.70

Calls 3

prepare_inputFunction · 0.85
chunkerFunction · 0.85
generate_tableFunction · 0.70

Tested by

no test coverage detected