Skip to content

Add typehints ciphers and bool alg #3264

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

Merged
Show file tree
Hide file tree
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
12 changes: 6 additions & 6 deletions boolean_algebra/quine_mc_cluskey.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def compare_string(string1, string2):
def compare_string(string1: str, string2: str) -> str:
"""
>>> compare_string('0010','0110')
'0_10'
Expand All @@ -19,7 +19,7 @@ def compare_string(string1, string2):
return "".join(l1)


def check(binary):
def check(binary: [str]) -> [str]:
"""
>>> check(['0.00.01.5'])
['0.00.01.5']
Expand All @@ -43,7 +43,7 @@ def check(binary):
binary = list(set(temp))


def decimal_to_binary(no_of_variable, minterms):
def decimal_to_binary(no_of_variable: int, minterms: [float]) -> [str]:
"""
>>> decimal_to_binary(3,[1.5])
['0.00.01.5']
Expand All @@ -59,7 +59,7 @@ def decimal_to_binary(no_of_variable, minterms):
return temp


def is_for_table(string1, string2, count):
def is_for_table(string1: str, string2: str, count: int) -> bool:
"""
>>> is_for_table('__1','011',2)
True
Expand All @@ -79,7 +79,7 @@ def is_for_table(string1, string2, count):
return False


def selection(chart, prime_implicants):
def selection(chart: [[int]], prime_implicants: [str]) -> [str]:
"""
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
Expand Down Expand Up @@ -126,7 +126,7 @@ def selection(chart, prime_implicants):
chart[j][i] = 0


def prime_implicant_chart(prime_implicants, binary):
def prime_implicant_chart(prime_implicants: [str], binary: [str]) -> [[int]]:
"""
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
[[1]]
Expand Down
4 changes: 2 additions & 2 deletions ciphers/affine_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def main():
print(f"\n{mode.title()}ed text: \n{translated}")


def check_keys(keyA, keyB, mode):
def check_keys(keyA: int, keyB: int, mode: str) -> None:
if mode == "encrypt":
if keyA == 1:
sys.exit(
Expand Down Expand Up @@ -90,7 +90,7 @@ def decrypt_message(key: int, message: str) -> str:
return plainText


def get_random_key():
def get_random_key() -> int:
while True:
keyA = random.randint(2, len(SYMBOLS))
keyB = random.randint(2, len(SYMBOLS))
Expand Down
4 changes: 2 additions & 2 deletions ciphers/base64_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def encode_base64(text):
def encode_base64(text: str) -> str:
r"""
>>> encode_base64('WELCOME to base64 encoding 😁')
'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ=='
Expand Down Expand Up @@ -33,7 +33,7 @@ def encode_base64(text):
return r[0 : len(r) - len(p)] + p


def decode_base64(text):
def decode_base64(text: str) -> str:
r"""
>>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==')
'WELCOME to base64 encoding 😁'
Expand Down
2 changes: 1 addition & 1 deletion ciphers/brute_force_caesar_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def decrypt(message):
def decrypt(message: str) -> None:
"""
>>> decrypt('TMDETUX PMDVU')
Decryption using Key #0: TMDETUX PMDVU
Expand Down
4 changes: 2 additions & 2 deletions ciphers/cryptomath_module.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
def gcd(a, b):
def gcd(a: int, b: int) -> int:
while a != 0:
a, b = b % a, a
return b


def findModInverse(a, m):
def findModInverse(a: int, m: int) -> int:
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
Expand Down
8 changes: 5 additions & 3 deletions ciphers/decrypt_caesar_with_chi_squared.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
#!/usr/bin/env python3

from typing import Tuple


def decrypt_caesar_with_chi_squared(
ciphertext: str,
cipher_alphabet=None,
frequencies_dict=None,
cipher_alphabet: str = None,
frequencies_dict: str = None,
case_sensetive: bool = False,
) -> tuple:
) -> Tuple[int, float, str]:
"""
Basic Usage
===========
Expand Down
4 changes: 2 additions & 2 deletions ciphers/deterministic_miller_rabin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""


def miller_rabin(n, allow_probable=False):
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.

Uses numerical analysis results to return whether or not the passed number
Expand Down Expand Up @@ -87,7 +87,7 @@ def miller_rabin(n, allow_probable=False):
return True


def test_miller_rabin():
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""
Expand Down
2 changes: 1 addition & 1 deletion ciphers/diffie.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def find_primitive(n):
def find_primitive(n: int) -> int:
for r in range(1, n):
li = []
for x in range(n - 1):
Expand Down
6 changes: 3 additions & 3 deletions ciphers/elgamal_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def main():
# so I used 4.80 Algorithm in
# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# and it seems to run nicely!
def primitiveRoot(p_val):
def primitiveRoot(p_val: int) -> int:
print("Generating primitive root of p")
while True:
g = random.randrange(3, p_val)
Expand All @@ -30,7 +30,7 @@ def primitiveRoot(p_val):
return g


def generateKey(keySize):
def generateKey(keySize: int) -> ((int, int, int, int), (int, int)):
print("Generating prime p...")
p = rabinMiller.generateLargePrime(keySize) # select large prime number.
e_1 = primitiveRoot(p) # one primitive root on modulo p.
Expand All @@ -43,7 +43,7 @@ def generateKey(keySize):
return publicKey, privateKey


def makeKeyFiles(name, keySize):
def makeKeyFiles(name: str, keySize: int):
if os.path.exists("%s_pubkey.txt" % name) or os.path.exists(
"%s_privkey.txt" % name
):
Expand Down
2 changes: 1 addition & 1 deletion ciphers/hill_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class HillCipher:

to_int = numpy.vectorize(lambda x: round(x))

def __init__(self, encrypt_key):
def __init__(self, encrypt_key: int):
"""
encrypt_key is an NxN numpy array
"""
Expand Down
2 changes: 1 addition & 1 deletion ciphers/mixed_keyword_cypher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def mixed_keyword(key="college", pt="UNIVERSITY"):
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
"""

For key:hello
Expand Down
4 changes: 2 additions & 2 deletions ciphers/morse_code_implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
}


def encrypt(message):
def encrypt(message: str) -> str:
cipher = ""
for letter in message:
if letter != " ":
Expand All @@ -69,7 +69,7 @@ def encrypt(message):
return cipher[:-1]


def decrypt(message):
def decrypt(message: str) -> str:
decipher = ""
letters = message.split(" ")
for letter in letters:
Expand Down
4 changes: 2 additions & 2 deletions ciphers/onepad_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


class Onepad:
def encrypt(self, text):
def encrypt(self, text: str) -> ([str], [int]):
"""Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text]
key = []
Expand All @@ -14,7 +14,7 @@ def encrypt(self, text):
key.append(k)
return cipher, key

def decrypt(self, cipher, key):
def decrypt(self, cipher: [str], key: [int]) -> str:
"""Function to decrypt text using pseudo-random numbers."""
plain = []
for i in range(len(key)):
Expand Down
8 changes: 4 additions & 4 deletions ciphers/playfair_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def chunker(seq, size):
yield chunk


def prepare_input(dirty):
def prepare_input(dirty: str) -> str:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
Expand All @@ -37,7 +37,7 @@ def prepare_input(dirty):
return clean


def generate_table(key):
def generate_table(key: str) -> [str]:

# I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters)
Expand All @@ -59,7 +59,7 @@ def generate_table(key):
return table


def encode(plaintext, key):
def encode(plaintext: str, key: str) -> str:
table = generate_table(key)
plaintext = prepare_input(plaintext)
ciphertext = ""
Expand All @@ -82,7 +82,7 @@ def encode(plaintext, key):
return ciphertext


def decode(ciphertext, key):
def decode(ciphertext: str, key: str) -> str:
table = generate_table(key)
plaintext = ""

Expand Down
10 changes: 5 additions & 5 deletions ciphers/porta_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
}


def generate_table(key):
def generate_table(key: str) -> [(str, str)]:
"""
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
Expand All @@ -38,7 +38,7 @@ def generate_table(key):
return [alphabet[char] for char in key.upper()]


def encrypt(key, words):
def encrypt(key: str, words: str) -> str:
"""
>>> encrypt('marvin', 'jessica')
'QRACRWU'
Expand All @@ -52,15 +52,15 @@ def encrypt(key, words):
return cipher


def decrypt(key, words):
def decrypt(key: str, words: str) -> str:
"""
>>> decrypt('marvin', 'QRACRWU')
'JESSICA'
"""
return encrypt(key, words)


def get_position(table, char):
def get_position(table: [(str, str)], char: str) -> (int, int) or (None, None):
"""
>>> table = [
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
Expand All @@ -76,7 +76,7 @@ def get_position(table, char):
return (None, None) if row == -1 else (row, table[row].index(char))


def get_opponent(table, char):
def get_opponent(table: [(str, str)], char: str) -> str:
"""
>>> table = [
... ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
Expand Down
6 changes: 3 additions & 3 deletions ciphers/rabin_miller.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import random


def rabinMiller(num):
def rabinMiller(num: int) -> bool:
s = num - 1
t = 0

Expand All @@ -25,7 +25,7 @@ def rabinMiller(num):
return True


def isPrime(num):
def isPrime(num: int) -> bool:
if num < 2:
return False

Expand Down Expand Up @@ -210,7 +210,7 @@ def isPrime(num):
return rabinMiller(num)


def generateLargePrime(keysize=1024):
def generateLargePrime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if isPrime(num):
Expand Down
2 changes: 1 addition & 1 deletion ciphers/rot13.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
def dencrypt(s: str, n: int = 13):
def dencrypt(s: str, n: int = 13) -> str:
"""
https://en.wikipedia.org/wiki/ROT13

Expand Down
Loading