Skip to content

Commit

Permalink
refactor: Move constants outside of variable scope (TheAlgorithms#7262)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Dhruv Manilawala <[email protected]>
Co-authored-by: Christian Clauss <[email protected]>
  • Loading branch information
4 people authored Oct 16, 2022
1 parent 7776411 commit c6582b3
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 97 deletions.
15 changes: 8 additions & 7 deletions ciphers/bifid.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,17 @@

import numpy as np

SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]


class BifidCipher:
def __init__(self) -> None:
SQUARE = [ # noqa: N806
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]
self.SQUARE = np.array(SQUARE)

def letter_to_numbers(self, letter: str) -> np.ndarray:
Expand Down
14 changes: 8 additions & 6 deletions ciphers/brute_force_caesar_cipher.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import string


def decrypt(message: str) -> None:
"""
>>> decrypt('TMDETUX PMDVU')
Expand Down Expand Up @@ -28,16 +31,15 @@ def decrypt(message: str) -> None:
Decryption using Key #24: VOFGVWZ ROFXW
Decryption using Key #25: UNEFUVY QNEWV
"""
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806
for key in range(len(LETTERS)):
for key in range(len(string.ascii_uppercase)):
translated = ""
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
if symbol in string.ascii_uppercase:
num = string.ascii_uppercase.find(symbol)
num = num - key
if num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
num = num + len(string.ascii_uppercase)
translated = translated + string.ascii_uppercase[num]
else:
translated = translated + symbol
print(f"Decryption using Key #{key}: {translated}")
Expand Down
16 changes: 9 additions & 7 deletions ciphers/polybius.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@

import numpy as np

SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]


class PolybiusCipher:
def __init__(self) -> None:
SQUARE = [ # noqa: N806
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]

self.SQUARE = np.array(SQUARE)

def letter_to_numbers(self, letter: str) -> np.ndarray:
Expand Down
13 changes: 7 additions & 6 deletions compression/peak_signal_to_noise_ratio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
import cv2
import numpy as np

PIXEL_MAX = 255.0

def psnr(original: float, contrast: float) -> float:

def peak_signal_to_noise_ratio(original: float, contrast: float) -> float:
mse = np.mean((original - contrast) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 255.0 # noqa: N806
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) # noqa: N806
return PSNR

return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))


def main() -> None:
Expand All @@ -34,11 +35,11 @@ def main() -> None:

# Value expected: 29.73dB
print("-- First Test --")
print(f"PSNR value is {psnr(original, contrast)} dB")
print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB")

# # Value expected: 31.53dB (Wikipedia Example)
print("\n-- Second Test --")
print(f"PSNR value is {psnr(original2, contrast2)} dB")
print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB")


if __name__ == "__main__":
Expand Down
39 changes: 20 additions & 19 deletions conversions/binary_to_hexadecimal.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
BITS_TO_HEX = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "a",
"1011": "b",
"1100": "c",
"1101": "d",
"1110": "e",
"1111": "f",
}


def bin_to_hexadecimal(binary_str: str) -> str:
"""
Converting a binary string into hexadecimal using Grouping Method
Expand All @@ -17,25 +37,6 @@ def bin_to_hexadecimal(binary_str: str) -> str:
...
ValueError: Empty string was passed to the function
"""
BITS_TO_HEX = { # noqa: N806
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "a",
"1011": "b",
"1100": "c",
"1101": "d",
"1110": "e",
"1111": "f",
}

# Sanitising parameter
binary_str = str(binary_str).strip()

Expand Down
11 changes: 4 additions & 7 deletions conversions/decimal_to_any.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Convert a positive Decimal Number to Any Other Representation"""

from string import ascii_uppercase

ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase}


def decimal_to_any(num: int, base: int) -> str:
"""
Expand Down Expand Up @@ -65,13 +69,6 @@ def decimal_to_any(num: int, base: int) -> str:
raise ValueError("base must be >= 2")
if base > 36:
raise ValueError("base must be <= 36")
# fmt: off
ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', # noqa: N806, E501
'16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L',
'22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R',
'28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X',
'34': 'Y', '35': 'Z'}
# fmt: on
new_value = ""
mod = 0
div = 0
Expand Down
32 changes: 17 additions & 15 deletions conversions/roman_numerals.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
ROMAN = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]


def roman_to_int(roman: str) -> int:
"""
LeetCode No. 13 Roman to Integer
Expand Down Expand Up @@ -29,21 +46,6 @@ def int_to_roman(number: int) -> str:
>>> all(int_to_roman(value) == key for key, value in tests.items())
True
"""
ROMAN = [ # noqa: N806
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
result = []
for (arabic, roman) in ROMAN:
(factor, number) = divmod(number, arabic)
Expand Down
7 changes: 4 additions & 3 deletions geodesy/haversine_distance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from math import asin, atan, cos, radians, sin, sqrt, tan

AXIS_A = 6378137.0
AXIS_B = 6356752.314245
RADIUS = 6378137


def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Expand Down Expand Up @@ -30,9 +34,6 @@ def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> fl
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0 # noqa: N806
AXIS_B = 6356752.314245 # noqa: N806
RADIUS = 6378137 # noqa: N806
# Equation parameters
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
flattening = (AXIS_A - AXIS_B) / AXIS_A
Expand Down
8 changes: 4 additions & 4 deletions geodesy/lamberts_ellipsoidal_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

from .haversine_distance import haversine_distance

AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137


def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
Expand Down Expand Up @@ -45,10 +49,6 @@ def lamberts_ellipsoidal_distance(

# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0 # noqa: N806
AXIS_B = 6356752.314245 # noqa: N806
EQUATORIAL_RADIUS = 6378137 # noqa: N806

# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
Expand Down
3 changes: 2 additions & 1 deletion hashes/adler32.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
source: https://en.wikipedia.org/wiki/Adler-32
"""

MOD_ADLER = 65521


def adler32(plain_text: str) -> int:
"""
Expand All @@ -20,7 +22,6 @@ def adler32(plain_text: str) -> int:
>>> adler32('go adler em all')
708642122
"""
MOD_ADLER = 65521 # noqa: N806
a = 1
b = 0
for plain_chr in plain_text:
Expand Down
12 changes: 6 additions & 6 deletions physics/n_body_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
from matplotlib import animation
from matplotlib import pyplot as plt

# Frame rate of the animation
INTERVAL = 20

# Time between time steps in seconds
DELTA_TIME = INTERVAL / 1000


class Body:
def __init__(
Expand Down Expand Up @@ -219,12 +225,6 @@ def plot(
Utility function to plot how the given body-system evolves over time.
No doctest provided since this function does not have a return value.
"""
# Frame rate of the animation
INTERVAL = 20 # noqa: N806

# Time between time steps in seconds
DELTA_TIME = INTERVAL / 1000 # noqa: N806

fig = plt.figure()
fig.canvas.set_window_title(title)
ax = plt.axes(
Expand Down
6 changes: 3 additions & 3 deletions project_euler/problem_054/test_poker_hand.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,12 @@ def test_compare_random(hand, other, expected):


def test_hand_sorted():
POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] # noqa: N806
list_copy = POKER_HANDS.copy()
poker_hands = [PokerHand(hand) for hand in SORTED_HANDS]
list_copy = poker_hands.copy()
shuffle(list_copy)
user_sorted = chain(sorted(list_copy))
for index, hand in enumerate(user_sorted):
assert hand == POKER_HANDS[index]
assert hand == poker_hands[index]


def test_custom_sort_five_high_straight():
Expand Down
8 changes: 4 additions & 4 deletions project_euler/problem_064/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ def continuous_fraction_period(n: int) -> int:
"""
numerator = 0.0
denominator = 1.0
ROOT = int(sqrt(n)) # noqa: N806
integer_part = ROOT
root = int(sqrt(n))
integer_part = root
period = 0
while integer_part != 2 * ROOT:
while integer_part != 2 * root:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((ROOT + numerator) / denominator)
integer_part = int((root + numerator) / denominator)
period += 1
return period

Expand Down
6 changes: 3 additions & 3 deletions project_euler/problem_097/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ def solution(n: int = 10) -> str:
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Invalid input")
MODULUS = 10**n # noqa: N806
NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1 # noqa: N806
return str(NUMBER % MODULUS)
modulus = 10**n
number = 28433 * (pow(2, 7830457, modulus)) + 1
return str(number % modulus)


if __name__ == "__main__":
Expand Down
3 changes: 2 additions & 1 deletion project_euler/problem_125/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
be written as the sum of consecutive squares.
"""

LIMIT = 10**8


def is_palindrome(n: int) -> bool:
"""
Expand All @@ -35,7 +37,6 @@ def solution() -> int:
Returns the sum of all numbers less than 1e8 that are both palindromic and
can be written as the sum of consecutive squares.
"""
LIMIT = 10**8 # noqa: N806
answer = set()
first_square = 1
sum_squares = 5
Expand Down
3 changes: 2 additions & 1 deletion sorts/radix_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"""
from __future__ import annotations

RADIX = 10


def radix_sort(list_of_ints: list[int]) -> list[int]:
"""
Expand All @@ -19,7 +21,6 @@ def radix_sort(list_of_ints: list[int]) -> list[int]:
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
True
"""
RADIX = 10 # noqa: N806
placement = 1
max_digit = max(list_of_ints)
while placement <= max_digit:
Expand Down
Loading

0 comments on commit c6582b3

Please sign in to comment.