Skip to content

Commit

Permalink
Add pep8-naming to pre-commit hooks and fixes incorrect naming conven…
Browse files Browse the repository at this point in the history
…tions (TheAlgorithms#7062)

* ci(pre-commit): Add pep8-naming to `pre-commit` hooks (TheAlgorithms#7038)

* refactor: Fix naming conventions (TheAlgorithms#7038)

* Update arithmetic_analysis/lu_decomposition.py

Co-authored-by: Christian Clauss <[email protected]>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* refactor(lu_decomposition): Replace `NDArray` with `ArrayLike` (TheAlgorithms#7038)

* chore: Fix naming conventions in doctests (TheAlgorithms#7038)

* fix: Temporarily disable project euler problem 104 (TheAlgorithms#7069)

* chore: Fix naming conventions in doctests (TheAlgorithms#7038)

Co-authored-by: Christian Clauss <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Oct 12, 2022
1 parent e2cd982 commit 07e991d
Show file tree
Hide file tree
Showing 140 changed files with 1,555 additions and 1,539 deletions.
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ repos:
- --ignore=E203,W503
- --max-complexity=25
- --max-line-length=88
additional_dependencies: [pep8-naming]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.982
Expand Down
6 changes: 3 additions & 3 deletions arithmetic_analysis/lu_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
from __future__ import annotations

import numpy as np
import numpy.typing as NDArray
from numpy import float64
from numpy.typing import ArrayLike


def lower_upper_decomposition(
table: NDArray[float64],
) -> tuple[NDArray[float64], NDArray[float64]]:
table: ArrayLike[float64],
) -> tuple[ArrayLike[float64], ArrayLike[float64]]:
"""Lower-Upper (LU) Decomposition
Example:
Expand Down
4 changes: 2 additions & 2 deletions backtracking/n_queens.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
solution = []


def isSafe(board: list[list[int]], row: int, column: int) -> bool:
def is_safe(board: list[list[int]], row: int, column: int) -> bool:
"""
This function returns a boolean value True if it is safe to place a queen there
considering the current state of the board.
Expand Down Expand Up @@ -63,7 +63,7 @@ def solve(board: list[list[int]], row: int) -> bool:
If all the combinations for that particular branch are successful the board is
reinitialized for the next possible combination.
"""
if isSafe(board, row, i):
if is_safe(board, row, i):
board[row][i] = 1
solve(board, row + 1)
board[row][i] = 0
Expand Down
52 changes: 27 additions & 25 deletions ciphers/affine_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,26 @@
)


def check_keys(keyA: int, keyB: int, mode: str) -> None:
def check_keys(key_a: int, key_b: int, mode: str) -> None:
if mode == "encrypt":
if keyA == 1:
if key_a == 1:
sys.exit(
"The affine cipher becomes weak when key "
"A is set to 1. Choose different key"
)
if keyB == 0:
if key_b == 0:
sys.exit(
"The affine cipher becomes weak when key "
"B is set to 0. Choose different key"
)
if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1:
sys.exit(
"Key A must be greater than 0 and key B must "
f"be between 0 and {len(SYMBOLS) - 1}."
)
if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
if cryptomath.gcd(key_a, len(SYMBOLS)) != 1:
sys.exit(
f"Key A {keyA} and the symbol set size {len(SYMBOLS)} "
f"Key A {key_a} and the symbol set size {len(SYMBOLS)} "
"are not relatively prime. Choose a different key."
)

Expand All @@ -39,16 +39,16 @@ def encrypt_message(key: int, message: str) -> str:
... 'substitution cipher.')
'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
"""
keyA, keyB = divmod(key, len(SYMBOLS))
check_keys(keyA, keyB, "encrypt")
cipherText = ""
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "encrypt")
cipher_text = ""
for symbol in message:
if symbol in SYMBOLS:
symIndex = SYMBOLS.find(symbol)
cipherText += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]
sym_index = SYMBOLS.find(symbol)
cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)]
else:
cipherText += symbol
return cipherText
cipher_text += symbol
return cipher_text


def decrypt_message(key: int, message: str) -> str:
Expand All @@ -57,25 +57,27 @@ def decrypt_message(key: int, message: str) -> str:
... '{xIp~{HL}Gi')
'The affine cipher is a type of monoalphabetic substitution cipher.'
"""
keyA, keyB = divmod(key, len(SYMBOLS))
check_keys(keyA, keyB, "decrypt")
plainText = ""
modInverseOfkeyA = cryptomath.find_mod_inverse(keyA, len(SYMBOLS))
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "decrypt")
plain_text = ""
mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS))
for symbol in message:
if symbol in SYMBOLS:
symIndex = SYMBOLS.find(symbol)
plainText += SYMBOLS[(symIndex - keyB) * modInverseOfkeyA % len(SYMBOLS)]
sym_index = SYMBOLS.find(symbol)
plain_text += SYMBOLS[
(sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS)
]
else:
plainText += symbol
return plainText
plain_text += symbol
return plain_text


def get_random_key() -> int:
while True:
keyA = random.randint(2, len(SYMBOLS))
keyB = random.randint(2, len(SYMBOLS))
if cryptomath.gcd(keyA, len(SYMBOLS)) == 1 and keyB % len(SYMBOLS) != 0:
return keyA * len(SYMBOLS) + keyB
key_b = random.randint(2, len(SYMBOLS))
key_b = random.randint(2, len(SYMBOLS))
if cryptomath.gcd(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0:
return key_b * len(SYMBOLS) + key_b


def main() -> None:
Expand Down
2 changes: 1 addition & 1 deletion ciphers/bifid.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

class BifidCipher:
def __init__(self) -> None:
SQUARE = [
SQUARE = [ # noqa: N806
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
Expand Down
2 changes: 1 addition & 1 deletion ciphers/brute_force_caesar_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def decrypt(message: str) -> None:
Decryption using Key #24: VOFGVWZ ROFXW
Decryption using Key #25: UNEFUVY QNEWV
"""
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806
for key in range(len(LETTERS)):
translated = ""
for symbol in message:
Expand Down
10 changes: 5 additions & 5 deletions ciphers/elgamal_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def primitive_root(p_val: int) -> int:

def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]:
print("Generating prime p...")
p = rabin_miller.generateLargePrime(key_size) # select large prime number.
p = rabin_miller.generate_large_prime(key_size) # select large prime number.
e_1 = primitive_root(p) # one primitive root on modulo p.
d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety.
e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p)
Expand All @@ -37,7 +37,7 @@ def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, i
return public_key, private_key


def make_key_files(name: str, keySize: int) -> None:
def make_key_files(name: str, key_size: int) -> None:
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
print("\nWARNING:")
print(
Expand All @@ -47,16 +47,16 @@ def make_key_files(name: str, keySize: int) -> None:
)
sys.exit()

publicKey, privateKey = generate_key(keySize)
public_key, private_key = generate_key(key_size)
print(f"\nWriting public key to file {name}_pubkey.txt...")
with open(f"{name}_pubkey.txt", "w") as fo:
fo.write(
"%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3])
"%d,%d,%d,%d" % (public_key[0], public_key[1], public_key[2], public_key[3])
)

print(f"Writing private key to file {name}_privkey.txt...")
with open(f"{name}_privkey.txt", "w") as fo:
fo.write("%d,%d" % (privateKey[0], privateKey[1]))
fo.write("%d,%d" % (private_key[0], private_key[1]))


def main() -> None:
Expand Down
4 changes: 2 additions & 2 deletions ciphers/hill_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,11 +201,11 @@ def decrypt(self, text: str) -> str:


def main() -> None:
N = int(input("Enter the order of the encryption key: "))
n = int(input("Enter the order of the encryption key: "))
hill_matrix = []

print("Enter each row of the encryption key with space separated integers")
for _ in range(N):
for _ in range(n):
row = [int(x) for x in input().split()]
hill_matrix.append(row)

Expand Down
2 changes: 1 addition & 1 deletion ciphers/polybius.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

class PolybiusCipher:
def __init__(self) -> None:
SQUARE = [
SQUARE = [ # noqa: N806
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
Expand Down
14 changes: 7 additions & 7 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: int) -> bool:
def rabin_miller(num: int) -> bool:
s = num - 1
t = 0

Expand All @@ -29,7 +29,7 @@ def is_prime_low_num(num: int) -> bool:
if num < 2:
return False

lowPrimes = [
low_primes = [
2,
3,
5,
Expand Down Expand Up @@ -200,24 +200,24 @@ def is_prime_low_num(num: int) -> bool:
997,
]

if num in lowPrimes:
if num in low_primes:
return True

for prime in lowPrimes:
for prime in low_primes:
if (num % prime) == 0:
return False

return rabinMiller(num)
return rabin_miller(num)


def generateLargePrime(keysize: int = 1024) -> int:
def generate_large_prime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num


if __name__ == "__main__":
num = generateLargePrime()
num = generate_large_prime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
14 changes: 7 additions & 7 deletions ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ def get_text_from_blocks(


def encrypt_message(
message: str, key: tuple[int, int], blockSize: int = DEFAULT_BLOCK_SIZE
message: str, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE
) -> list[int]:
encrypted_blocks = []
n, e = key

for block in get_blocks_from_text(message, blockSize):
for block in get_blocks_from_text(message, block_size):
encrypted_blocks.append(pow(block, e, n))
return encrypted_blocks

Expand All @@ -63,8 +63,8 @@ def decrypt_message(
def read_key_file(key_filename: str) -> tuple[int, int, int]:
with open(key_filename) as fo:
content = fo.read()
key_size, n, EorD = content.split(",")
return (int(key_size), int(n), int(EorD))
key_size, n, eor_d = content.split(",")
return (int(key_size), int(n), int(eor_d))


def encrypt_and_write_to_file(
Expand Down Expand Up @@ -125,15 +125,15 @@ def main() -> None:

if mode == "encrypt":
if not os.path.exists("rsa_pubkey.txt"):
rkg.makeKeyFiles("rsa", 1024)
rkg.make_key_files("rsa", 1024)

message = input("\nEnter message: ")
pubkey_filename = "rsa_pubkey.txt"
print(f"Encrypting and writing to {filename}...")
encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message)
encrypted_text = encrypt_and_write_to_file(filename, pubkey_filename, message)

print("\nEncrypted text:")
print(encryptedText)
print(encrypted_text)

elif mode == "decrypt":
privkey_filename = "rsa_privkey.txt"
Expand Down
10 changes: 5 additions & 5 deletions ciphers/rsa_factorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import random


def rsafactor(d: int, e: int, N: int) -> list[int]:
def rsafactor(d: int, e: int, n: int) -> list[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
Expand All @@ -35,16 +35,16 @@ def rsafactor(d: int, e: int, N: int) -> list[int]:
p = 0
q = 0
while p == 0:
g = random.randint(2, N - 1)
g = random.randint(2, n - 1)
t = k
while True:
if t % 2 == 0:
t = t // 2
x = (g**t) % N
y = math.gcd(x - 1, N)
x = (g**t) % n
y = math.gcd(x - 1, n)
if x > 1 and y > 1:
p = y
q = N // y
q = n // y
break # find the correct factors
else:
break # t is not divisible by 2, break and choose another g
Expand Down
Loading

0 comments on commit 07e991d

Please sign in to comment.