refactor: Move constants outside of variable scope (#7262)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Caeden 2022-10-16 10:33:29 +01:00 committed by GitHub
parent 7776411621
commit c6582b35bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 107 additions and 97 deletions

View File

@ -9,16 +9,17 @@ https://www.braingle.com/brainteasers/codes/bifid.php
import numpy as np 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: class BifidCipher:
def __init__(self) -> None: 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) self.SQUARE = np.array(SQUARE)
def letter_to_numbers(self, letter: str) -> np.ndarray: def letter_to_numbers(self, letter: str) -> np.ndarray:

View File

@ -1,3 +1,6 @@
import string
def decrypt(message: str) -> None: def decrypt(message: str) -> None:
""" """
>>> decrypt('TMDETUX PMDVU') >>> decrypt('TMDETUX PMDVU')
@ -28,16 +31,15 @@ def decrypt(message: str) -> None:
Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #24: VOFGVWZ ROFXW
Decryption using Key #25: UNEFUVY QNEWV Decryption using Key #25: UNEFUVY QNEWV
""" """
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806 for key in range(len(string.ascii_uppercase)):
for key in range(len(LETTERS)):
translated = "" translated = ""
for symbol in message: for symbol in message:
if symbol in LETTERS: if symbol in string.ascii_uppercase:
num = LETTERS.find(symbol) num = string.ascii_uppercase.find(symbol)
num = num - key num = num - key
if num < 0: if num < 0:
num = num + len(LETTERS) num = num + len(string.ascii_uppercase)
translated = translated + LETTERS[num] translated = translated + string.ascii_uppercase[num]
else: else:
translated = translated + symbol translated = translated + symbol
print(f"Decryption using Key #{key}: {translated}") print(f"Decryption using Key #{key}: {translated}")

View File

@ -8,16 +8,18 @@ https://www.braingle.com/brainteasers/codes/polybius.php
import numpy as np 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: class PolybiusCipher:
def __init__(self) -> None: 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) self.SQUARE = np.array(SQUARE)
def letter_to_numbers(self, letter: str) -> np.ndarray: def letter_to_numbers(self, letter: str) -> np.ndarray:

View File

@ -11,14 +11,15 @@ import os
import cv2 import cv2
import numpy as np 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) mse = np.mean((original - contrast) ** 2)
if mse == 0: if mse == 0:
return 100 return 100
PIXEL_MAX = 255.0 # noqa: N806
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) # noqa: N806 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
return PSNR
def main() -> None: def main() -> None:
@ -34,11 +35,11 @@ def main() -> None:
# Value expected: 29.73dB # Value expected: 29.73dB
print("-- First Test --") 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) # # Value expected: 31.53dB (Wikipedia Example)
print("\n-- Second Test --") 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__": if __name__ == "__main__":

View File

@ -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: def bin_to_hexadecimal(binary_str: str) -> str:
""" """
Converting a binary string into hexadecimal using Grouping Method Converting a binary string into hexadecimal using Grouping Method
@ -17,25 +37,6 @@ def bin_to_hexadecimal(binary_str: str) -> str:
... ...
ValueError: Empty string was passed to the function 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 # Sanitising parameter
binary_str = str(binary_str).strip() binary_str = str(binary_str).strip()

View File

@ -1,5 +1,9 @@
"""Convert a positive Decimal Number to Any Other Representation""" """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: def decimal_to_any(num: int, base: int) -> str:
""" """
@ -65,13 +69,6 @@ def decimal_to_any(num: int, base: int) -> str:
raise ValueError("base must be >= 2") raise ValueError("base must be >= 2")
if base > 36: if base > 36:
raise ValueError("base must be <= 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 = "" new_value = ""
mod = 0 mod = 0
div = 0 div = 0

View File

@ -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: def roman_to_int(roman: str) -> int:
""" """
LeetCode No. 13 Roman to Integer LeetCode No. 13 Roman to Integer
@ -29,21 +46,6 @@ def int_to_roman(number: int) -> str:
>>> all(int_to_roman(value) == key for key, value in tests.items()) >>> all(int_to_roman(value) == key for key, value in tests.items())
True 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 = [] result = []
for (arabic, roman) in ROMAN: for (arabic, roman) in ROMAN:
(factor, number) = divmod(number, arabic) (factor, number) = divmod(number, arabic)

View File

@ -1,5 +1,9 @@
from math import asin, atan, cos, radians, sin, sqrt, tan 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: def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
""" """
@ -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 # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m) # Distance in metres(m)
AXIS_A = 6378137.0 # noqa: N806
AXIS_B = 6356752.314245 # noqa: N806
RADIUS = 6378137 # noqa: N806
# Equation parameters # Equation parameters
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
flattening = (AXIS_A - AXIS_B) / AXIS_A flattening = (AXIS_A - AXIS_B) / AXIS_A

View File

@ -2,6 +2,10 @@ from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance from .haversine_distance import haversine_distance
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137
def lamberts_ellipsoidal_distance( def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float lat1: float, lon1: float, lat2: float, lon2: float
@ -45,10 +49,6 @@ def lamberts_ellipsoidal_distance(
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m) # Distance in metres(m)
AXIS_A = 6378137.0 # noqa: N806
AXIS_B = 6356752.314245 # noqa: N806
EQUATORIAL_RADIUS = 6378137 # noqa: N806
# Equation Parameters # Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines # https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A flattening = (AXIS_A - AXIS_B) / AXIS_A

View File

@ -8,6 +8,8 @@
source: https://en.wikipedia.org/wiki/Adler-32 source: https://en.wikipedia.org/wiki/Adler-32
""" """
MOD_ADLER = 65521
def adler32(plain_text: str) -> int: def adler32(plain_text: str) -> int:
""" """
@ -20,7 +22,6 @@ def adler32(plain_text: str) -> int:
>>> adler32('go adler em all') >>> adler32('go adler em all')
708642122 708642122
""" """
MOD_ADLER = 65521 # noqa: N806
a = 1 a = 1
b = 0 b = 0
for plain_chr in plain_text: for plain_chr in plain_text:

View File

@ -19,6 +19,12 @@ import random
from matplotlib import animation from matplotlib import animation
from matplotlib import pyplot as plt 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: class Body:
def __init__( def __init__(
@ -219,12 +225,6 @@ def plot(
Utility function to plot how the given body-system evolves over time. Utility function to plot how the given body-system evolves over time.
No doctest provided since this function does not have a return value. 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 = plt.figure()
fig.canvas.set_window_title(title) fig.canvas.set_window_title(title)
ax = plt.axes( ax = plt.axes(

View File

@ -185,12 +185,12 @@ def test_compare_random(hand, other, expected):
def test_hand_sorted(): def test_hand_sorted():
POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] # noqa: N806 poker_hands = [PokerHand(hand) for hand in SORTED_HANDS]
list_copy = POKER_HANDS.copy() list_copy = poker_hands.copy()
shuffle(list_copy) shuffle(list_copy)
user_sorted = chain(sorted(list_copy)) user_sorted = chain(sorted(list_copy))
for index, hand in enumerate(user_sorted): for index, hand in enumerate(user_sorted):
assert hand == POKER_HANDS[index] assert hand == poker_hands[index]
def test_custom_sort_five_high_straight(): def test_custom_sort_five_high_straight():

View File

@ -33,13 +33,13 @@ def continuous_fraction_period(n: int) -> int:
""" """
numerator = 0.0 numerator = 0.0
denominator = 1.0 denominator = 1.0
ROOT = int(sqrt(n)) # noqa: N806 root = int(sqrt(n))
integer_part = ROOT integer_part = root
period = 0 period = 0
while integer_part != 2 * ROOT: while integer_part != 2 * root:
numerator = denominator * integer_part - numerator numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator denominator = (n - numerator**2) / denominator
integer_part = int((ROOT + numerator) / denominator) integer_part = int((root + numerator) / denominator)
period += 1 period += 1
return period return period

View File

@ -34,9 +34,9 @@ def solution(n: int = 10) -> str:
""" """
if not isinstance(n, int) or n < 0: if not isinstance(n, int) or n < 0:
raise ValueError("Invalid input") raise ValueError("Invalid input")
MODULUS = 10**n # noqa: N806 modulus = 10**n
NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1 # noqa: N806 number = 28433 * (pow(2, 7830457, modulus)) + 1
return str(NUMBER % MODULUS) return str(number % modulus)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -13,6 +13,8 @@ Find the sum of all the numbers less than 10^8 that are both palindromic and can
be written as the sum of consecutive squares. be written as the sum of consecutive squares.
""" """
LIMIT = 10**8
def is_palindrome(n: int) -> bool: def is_palindrome(n: int) -> bool:
""" """
@ -35,7 +37,6 @@ def solution() -> int:
Returns the sum of all numbers less than 1e8 that are both palindromic and Returns the sum of all numbers less than 1e8 that are both palindromic and
can be written as the sum of consecutive squares. can be written as the sum of consecutive squares.
""" """
LIMIT = 10**8 # noqa: N806
answer = set() answer = set()
first_square = 1 first_square = 1
sum_squares = 5 sum_squares = 5

View File

@ -5,6 +5,8 @@ Source: https://en.wikipedia.org/wiki/Radix_sort
""" """
from __future__ import annotations from __future__ import annotations
RADIX = 10
def radix_sort(list_of_ints: list[int]) -> list[int]: def radix_sort(list_of_ints: list[int]) -> list[int]:
""" """
@ -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]) >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
True True
""" """
RADIX = 10 # noqa: N806
placement = 1 placement = 1
max_digit = max(list_of_ints) max_digit = max(list_of_ints)
while placement <= max_digit: while placement <= max_digit:

View File

@ -10,15 +10,15 @@ import pprint
import requests import requests
API_ENDPOINT_URL = "https://zenquotes.io/api"
def quote_of_the_day() -> list: def quote_of_the_day() -> list:
API_ENDPOINT_URL = "https://zenquotes.io/api/today/" # noqa: N806 return requests.get(API_ENDPOINT_URL + "/today").json()
return requests.get(API_ENDPOINT_URL).json()
def random_quotes() -> list: def random_quotes() -> list:
API_ENDPOINT_URL = "https://zenquotes.io/api/random/" # noqa: N806 return requests.get(API_ENDPOINT_URL + "/random").json()
return requests.get(API_ENDPOINT_URL).json()
if __name__ == "__main__": if __name__ == "__main__":