Skip to content

cipher: add scytale cipher #12395

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions ciphers/columnar_transposition_cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import math


def encrypt_columnar_cipher(message: str, key: str) -> str:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file ciphers/columnar_transposition_cipher.py, please provide doctest for the function encrypt_columnar_cipher

"""
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.
"""
# Remove spaces and calculate dimensions
message = message.replace(" ", "")
num_cols = len(key)
num_rows = math.ceil(len(message) / num_cols)

Check failure on line 15 in ciphers/columnar_transposition_cipher.py

GitHub Actions / ruff

Ruff (F841)

ciphers/columnar_transposition_cipher.py:15:5: F841 Local variable `num_rows` is assigned to but never used

# Fill the grid with characters
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])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: k

ciphertext = "".join([grid[i] for i in sorted_key_indices])

return ciphertext


def decrypt_columnar_cipher(ciphertext: str, key: str) -> str:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file ciphers/columnar_transposition_cipher.py, please provide doctest for the function decrypt_columnar_cipher

"""
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.
"""
num_cols = len(key)
num_rows = math.ceil(len(ciphertext) / num_cols)
num_shaded_boxes = (num_cols * num_rows) - len(ciphertext)

# Sort columns based on the key order
sorted_key_indices = sorted(range(len(key)), key=lambda k: key[k])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: k

col_lengths = [num_rows] * num_cols
for i in range(num_shaded_boxes):
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])
start += col_length

# Rebuild plaintext row by row
plaintext = ""
for i in range(num_rows):
for j in range(num_cols):
if i < len(grid[sorted_key_indices[j]]):
plaintext += grid[sorted_key_indices[j]][i]

return plaintext


# Example usage
message = "HELLO WORLD FROM COLUMNAR"
key = "3412"

# Encrypt the message
encrypted = encrypt_columnar_cipher(message, key)
print("Encrypted:", encrypted)

# Decrypt the message
decrypted = decrypt_columnar_cipher(encrypted, key)
print("Decrypted:", decrypted)
59 changes: 59 additions & 0 deletions ciphers/scytale_cipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
def encrypt_scytale_cipher(message: str, key: int) -> str:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file ciphers/scytale_cipher.py, please provide doctest for the function encrypt_scytale_cipher

"""
Encrypts a message using the Scytale Cipher.

:param message: Text to encrypt.
:param key: Number of rows (key).
:return: Encrypted message.
"""
message = message.replace(" ", "") # Optional: remove spaces
ciphertext = [""] * key

# Distribute characters across rows based on the key
for i in range(len(message)):
ciphertext[i % key] += message[i]

return "".join(ciphertext)


def decrypt_scytale_cipher(ciphertext: str, key: int) -> str:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file ciphers/scytale_cipher.py, please provide doctest for the function decrypt_scytale_cipher

"""
Decrypts a message encrypted with the Scytale Cipher.

:param ciphertext: Encrypted text.
:param key: Number of rows (key).
:return: Decrypted message.
"""
num_cols = -(-len(ciphertext) // key) # Calculate number of columns (round up)
num_rows = key
num_shaded_boxes = (num_cols * num_rows) - len(ciphertext) # Extra unused boxes

plaintext = [""] * num_cols
col = 0
row = 0

# Rebuild the plaintext row by row
for char in ciphertext:
plaintext[col] += char
col += 1
# Reset column and move to next row if end of column is reached
if (col == num_cols) or (
col == num_cols - 1 and row >= num_rows - num_shaded_boxes
):
col = 0
row += 1

return "".join(plaintext)


# Example usage
message = "HELLO WORLD FROM SCYTALE"
key = 5

# Encrypt the message
ciphered = encrypt_scytale_cipher(message, key)
print("Encrypted:", ciphered)

# Decrypt the message
deciphered = decrypt_scytale_cipher(ciphered, key)
print("Decrypted:", deciphered)

Unchanged files with check annotations Beta

alive = cells[i][j] == 1
if (
(alive and 2 <= neighbour_count <= 3)
or not alive
and neighbour_count == 3

Check failure on line 64 in cellular_automata/conways_game_of_life.py

GitHub Actions / ruff

Ruff (RUF021)

cellular_automata/conways_game_of_life.py:63:20: RUF021 Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear
):
next_generation_row.append(1)
else:
from collections.abc import Generator, Iterable
def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]:

Check failure on line 27 in ciphers/playfair_cipher.py

GitHub Actions / ruff

Ruff (UP043)

ciphers/playfair_cipher.py:27:47: UP043 Unnecessary default type arguments
it = iter(seq)
while True:
chunk = tuple(itertools.islice(it, size))
key_no_dups = ""
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():

Check failure on line 13 in ciphers/simple_keyword_cypher.py

GitHub Actions / ruff

Ruff (RUF021)

ciphers/simple_keyword_cypher.py:13:25: RUF021 Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear
key_no_dups += ch
return key_no_dups
if (
(col == num_cols)
or (col == num_cols - 1)
and (row >= num_rows - num_shaded_boxes)

Check failure on line 58 in ciphers/transposition_cipher.py

GitHub Actions / ruff

Ruff (RUF021)

ciphers/transposition_cipher.py:57:16: RUF021 Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear
):
col = 0
row += 1
lexicon[curr_string + "0"] = last_match_id
if math.log2(index).is_integer():
for curr_key in lexicon:
lexicon[curr_key] = "0" + lexicon[curr_key]

Check failure on line 39 in compression/lempel_ziv.py

GitHub Actions / ruff

Ruff (PLC0206)

compression/lempel_ziv.py:38:9: PLC0206 Extracting value from dictionary without calling `.items()`
lexicon[curr_string + "1"] = bin(index)[2:]
times, results = zip(*[time_solve(grid) for grid in grids])
if (n := len(grids)) > 1:
print(
"Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)."

Check failure on line 159 in data_structures/arrays/sudoku_solver.py

GitHub Actions / ruff

Ruff (UP031)

data_structures/arrays/sudoku_solver.py:159:13: UP031 Use format specifiers instead of percent format
% (sum(results), n, name, sum(times) / n, n / sum(times), max(times))
)
return tree
def preorder(root: Node | None) -> Generator[int, None, None]:

Check failure on line 33 in data_structures/binary_tree/binary_tree_traversals.py

GitHub Actions / ruff

Ruff (UP043)

data_structures/binary_tree/binary_tree_traversals.py:33:36: UP043 Unnecessary default type arguments
"""
Pre-order traversal visits root node, left subtree, right subtree.
>>> list(preorder(make_tree()))
yield from preorder(root.right)
def postorder(root: Node | None) -> Generator[int, None, None]:

Check failure on line 46 in data_structures/binary_tree/binary_tree_traversals.py

GitHub Actions / ruff

Ruff (UP043)

data_structures/binary_tree/binary_tree_traversals.py:46:37: UP043 Unnecessary default type arguments
"""
Post-order traversal visits left subtree, right subtree, root node.
>>> list(postorder(make_tree()))
yield root.data
def inorder(root: Node | None) -> Generator[int, None, None]:

Check failure on line 59 in data_structures/binary_tree/binary_tree_traversals.py

GitHub Actions / ruff

Ruff (UP043)

data_structures/binary_tree/binary_tree_traversals.py:59:35: UP043 Unnecessary default type arguments
"""
In-order traversal visits left subtree, root node, right subtree.
>>> list(inorder(make_tree()))