Skip to content
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

Track Solutions #26

Open
wants to merge 41 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
affine cipher
Aayush Badoni authored and Aayush Badoni committed Apr 12, 2024
commit 3ddc88f56fafbc7509becd870c9099785914ec08
Binary file not shown.
Binary file not shown.
60 changes: 57 additions & 3 deletions practice/affine-cipher/affine_cipher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,60 @@
def encode(plain_text, a, b):
pass
"""
Approach:
- The provided code implements a simple affine cipher, which is a type of substitution cipher.
- The `encode` function encodes plain text using the formula E(x) = (ax + b) mod m, where 'a' and 'm' are coprime, and 'b' is any integer.
- The `decode` function decodes the ciphered text using the formula D(x) = a^(-1)(x - b) mod m.
- The `is_coprime` function checks whether two numbers are coprime.
- The implementation ensures that 'a' and the length of the alphabet are coprime to ensure that every letter is mapped to a unique value.
"""

import math
import string

def is_coprime(x, y):
return math.gcd(x, y) == 1

def encode(plain_text, a, b):
alphabet = list(string.ascii_lowercase)
numbers = list(string.digits)
if not is_coprime(a, len(alphabet)):
raise ValueError("a and m must be coprime.")
indexes = []
for letter in plain_text.lower():
if letter in alphabet:
indexes.append((a * alphabet.index(letter) + b) % len(alphabet))
elif letter in numbers:
indexes.append(int(letter) + 1000)
out = ""
for place, index in enumerate(indexes):
if place % 5 == 0 and place > 1:
out += " "
if index < len(alphabet):
out += alphabet[index]
else:
out += str(index - 1000)
else:
if index < len(alphabet):
out += alphabet[index]
else:
out += str(index - 1000)
return out

def decode(ciphered_text, a, b):
pass
alphabet = list(string.ascii_lowercase)
numbers = list(string.digits)
if not is_coprime(a, len(alphabet)):
raise ValueError("a and m must be coprime.")
indexes = []
for letter in ciphered_text:
if letter in numbers:
indexes.append(int(letter) + 1000)
elif letter in alphabet:
indexes.append(
pow(a, -1, len(alphabet)) * (alphabet.index(letter) - b) % len(alphabet)
)
return "".join(
[
str(letter - 1000) if letter > len(alphabet) else alphabet[letter]
for letter in indexes
]
)