mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-20 00:02:04 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
47adce5867
commit
a23b0f5177
|
@ -1,9 +1,10 @@
|
|||
import math
|
||||
|
||||
|
||||
def encrypt_columnar_cipher(message: str, key: str) -> str:
|
||||
"""
|
||||
Encrypts a message using the Columnar Transposition Cipher.
|
||||
|
||||
|
||||
:param message: Text to encrypt.
|
||||
:param key: String key used to define column order.
|
||||
:return: Encrypted message.
|
||||
|
@ -12,15 +13,15 @@ def encrypt_columnar_cipher(message: str, key: str) -> str:
|
|||
message = message.replace(" ", "")
|
||||
num_cols = len(key)
|
||||
num_rows = math.ceil(len(message) / num_cols)
|
||||
|
||||
|
||||
# Fill the grid with characters
|
||||
grid = [''] * num_cols
|
||||
grid = [""] * num_cols
|
||||
for i, char in enumerate(message):
|
||||
grid[i % num_cols] += char
|
||||
|
||||
# Sort columns based on the key order
|
||||
sorted_key_indices = sorted(range(len(key)), key=lambda k: key[k])
|
||||
ciphertext = ''.join([grid[i] for i in sorted_key_indices])
|
||||
ciphertext = "".join([grid[i] for i in sorted_key_indices])
|
||||
|
||||
return ciphertext
|
||||
|
||||
|
@ -28,7 +29,7 @@ def encrypt_columnar_cipher(message: str, key: str) -> str:
|
|||
def decrypt_columnar_cipher(ciphertext: str, key: str) -> str:
|
||||
"""
|
||||
Decrypts a message encrypted with the Columnar Transposition Cipher.
|
||||
|
||||
|
||||
:param ciphertext: Encrypted text.
|
||||
:param key: String key used to define column order.
|
||||
:return: Decrypted message.
|
||||
|
@ -41,17 +42,17 @@ def decrypt_columnar_cipher(ciphertext: str, key: str) -> str:
|
|||
sorted_key_indices = sorted(range(len(key)), key=lambda k: key[k])
|
||||
col_lengths = [num_rows] * num_cols
|
||||
for i in range(num_shaded_boxes):
|
||||
col_lengths[sorted_key_indices[-(i+1)]] -= 1
|
||||
col_lengths[sorted_key_indices[-(i + 1)]] -= 1
|
||||
|
||||
# Distribute ciphertext into columns based on the sorted key
|
||||
grid = []
|
||||
start = 0
|
||||
for col_length in col_lengths:
|
||||
grid.append(ciphertext[start:start + col_length])
|
||||
grid.append(ciphertext[start : start + col_length])
|
||||
start += col_length
|
||||
|
||||
# Rebuild plaintext row by row
|
||||
plaintext = ''
|
||||
plaintext = ""
|
||||
for i in range(num_rows):
|
||||
for j in range(num_cols):
|
||||
if i < len(grid[sorted_key_indices[j]]):
|
||||
|
|
Loading…
Reference in New Issue
Block a user