Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c6582b3

Browse files
CaedenPHpre-commit-ci[bot]dhruvmanilacclauss
authoredOct 16, 2022
refactor: Move constants outside of variable scope (TheAlgorithms#7262)
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]>
1 parent 7776411 commit c6582b3

17 files changed

+107
-97
lines changed
 

‎ciphers/bifid.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,17 @@
99

1010
import numpy as np
1111

12+
SQUARE = [
13+
["a", "b", "c", "d", "e"],
14+
["f", "g", "h", "i", "k"],
15+
["l", "m", "n", "o", "p"],
16+
["q", "r", "s", "t", "u"],
17+
["v", "w", "x", "y", "z"],
18+
]
19+
1220

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

2425
def letter_to_numbers(self, letter: str) -> np.ndarray:

‎ciphers/brute_force_caesar_cipher.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import string
2+
3+
14
def decrypt(message: str) -> None:
25
"""
36
>>> decrypt('TMDETUX PMDVU')
@@ -28,16 +31,15 @@ def decrypt(message: str) -> None:
2831
Decryption using Key #24: VOFGVWZ ROFXW
2932
Decryption using Key #25: UNEFUVY QNEWV
3033
"""
31-
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806
32-
for key in range(len(LETTERS)):
34+
for key in range(len(string.ascii_uppercase)):
3335
translated = ""
3436
for symbol in message:
35-
if symbol in LETTERS:
36-
num = LETTERS.find(symbol)
37+
if symbol in string.ascii_uppercase:
38+
num = string.ascii_uppercase.find(symbol)
3739
num = num - key
3840
if num < 0:
39-
num = num + len(LETTERS)
40-
translated = translated + LETTERS[num]
41+
num = num + len(string.ascii_uppercase)
42+
translated = translated + string.ascii_uppercase[num]
4143
else:
4244
translated = translated + symbol
4345
print(f"Decryption using Key #{key}: {translated}")

‎ciphers/polybius.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,18 @@
88

99
import numpy as np
1010

11+
SQUARE = [
12+
["a", "b", "c", "d", "e"],
13+
["f", "g", "h", "i", "k"],
14+
["l", "m", "n", "o", "p"],
15+
["q", "r", "s", "t", "u"],
16+
["v", "w", "x", "y", "z"],
17+
]
18+
1119

1220
class PolybiusCipher:
1321
def __init__(self) -> None:
14-
SQUARE = [ # noqa: N806
15-
["a", "b", "c", "d", "e"],
16-
["f", "g", "h", "i", "k"],
17-
["l", "m", "n", "o", "p"],
18-
["q", "r", "s", "t", "u"],
19-
["v", "w", "x", "y", "z"],
20-
]
22+
2123
self.SQUARE = np.array(SQUARE)
2224

2325
def letter_to_numbers(self, letter: str) -> np.ndarray:

‎compression/peak_signal_to_noise_ratio.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,15 @@
1111
import cv2
1212
import numpy as np
1313

14+
PIXEL_MAX = 255.0
1415

15-
def psnr(original: float, contrast: float) -> float:
16+
17+
def peak_signal_to_noise_ratio(original: float, contrast: float) -> float:
1618
mse = np.mean((original - contrast) ** 2)
1719
if mse == 0:
1820
return 100
19-
PIXEL_MAX = 255.0 # noqa: N806
20-
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) # noqa: N806
21-
return PSNR
21+
22+
return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
2223

2324

2425
def main() -> None:
@@ -34,11 +35,11 @@ def main() -> None:
3435

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

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

4344

4445
if __name__ == "__main__":

‎conversions/binary_to_hexadecimal.py

+20-19
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
1+
BITS_TO_HEX = {
2+
"0000": "0",
3+
"0001": "1",
4+
"0010": "2",
5+
"0011": "3",
6+
"0100": "4",
7+
"0101": "5",
8+
"0110": "6",
9+
"0111": "7",
10+
"1000": "8",
11+
"1001": "9",
12+
"1010": "a",
13+
"1011": "b",
14+
"1100": "c",
15+
"1101": "d",
16+
"1110": "e",
17+
"1111": "f",
18+
}
19+
20+
121
def bin_to_hexadecimal(binary_str: str) -> str:
222
"""
323
Converting a binary string into hexadecimal using Grouping Method
@@ -17,25 +37,6 @@ def bin_to_hexadecimal(binary_str: str) -> str:
1737
...
1838
ValueError: Empty string was passed to the function
1939
"""
20-
BITS_TO_HEX = { # noqa: N806
21-
"0000": "0",
22-
"0001": "1",
23-
"0010": "2",
24-
"0011": "3",
25-
"0100": "4",
26-
"0101": "5",
27-
"0110": "6",
28-
"0111": "7",
29-
"1000": "8",
30-
"1001": "9",
31-
"1010": "a",
32-
"1011": "b",
33-
"1100": "c",
34-
"1101": "d",
35-
"1110": "e",
36-
"1111": "f",
37-
}
38-
3940
# Sanitising parameter
4041
binary_str = str(binary_str).strip()
4142

‎conversions/decimal_to_any.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
"""Convert a positive Decimal Number to Any Other Representation"""
22

3+
from string import ascii_uppercase
4+
5+
ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase}
6+
37

48
def decimal_to_any(num: int, base: int) -> str:
59
"""
@@ -65,13 +69,6 @@ def decimal_to_any(num: int, base: int) -> str:
6569
raise ValueError("base must be >= 2")
6670
if base > 36:
6771
raise ValueError("base must be <= 36")
68-
# fmt: off
69-
ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', # noqa: N806, E501
70-
'16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L',
71-
'22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R',
72-
'28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X',
73-
'34': 'Y', '35': 'Z'}
74-
# fmt: on
7572
new_value = ""
7673
mod = 0
7774
div = 0

‎conversions/roman_numerals.py

+17-15
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,20 @@
1+
ROMAN = [
2+
(1000, "M"),
3+
(900, "CM"),
4+
(500, "D"),
5+
(400, "CD"),
6+
(100, "C"),
7+
(90, "XC"),
8+
(50, "L"),
9+
(40, "XL"),
10+
(10, "X"),
11+
(9, "IX"),
12+
(5, "V"),
13+
(4, "IV"),
14+
(1, "I"),
15+
]
16+
17+
118
def roman_to_int(roman: str) -> int:
219
"""
320
LeetCode No. 13 Roman to Integer
@@ -29,21 +46,6 @@ def int_to_roman(number: int) -> str:
2946
>>> all(int_to_roman(value) == key for key, value in tests.items())
3047
True
3148
"""
32-
ROMAN = [ # noqa: N806
33-
(1000, "M"),
34-
(900, "CM"),
35-
(500, "D"),
36-
(400, "CD"),
37-
(100, "C"),
38-
(90, "XC"),
39-
(50, "L"),
40-
(40, "XL"),
41-
(10, "X"),
42-
(9, "IX"),
43-
(5, "V"),
44-
(4, "IV"),
45-
(1, "I"),
46-
]
4749
result = []
4850
for (arabic, roman) in ROMAN:
4951
(factor, number) = divmod(number, arabic)

‎geodesy/haversine_distance.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
from math import asin, atan, cos, radians, sin, sqrt, tan
22

3+
AXIS_A = 6378137.0
4+
AXIS_B = 6356752.314245
5+
RADIUS = 6378137
6+
37

48
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
59
"""
@@ -30,9 +34,6 @@ def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> fl
3034
"""
3135
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
3236
# Distance in metres(m)
33-
AXIS_A = 6378137.0 # noqa: N806
34-
AXIS_B = 6356752.314245 # noqa: N806
35-
RADIUS = 6378137 # noqa: N806
3637
# Equation parameters
3738
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
3839
flattening = (AXIS_A - AXIS_B) / AXIS_A

‎geodesy/lamberts_ellipsoidal_distance.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
from .haversine_distance import haversine_distance
44

5+
AXIS_A = 6378137.0
6+
AXIS_B = 6356752.314245
7+
EQUATORIAL_RADIUS = 6378137
8+
59

610
def lamberts_ellipsoidal_distance(
711
lat1: float, lon1: float, lat2: float, lon2: float
@@ -45,10 +49,6 @@ def lamberts_ellipsoidal_distance(
4549

4650
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
4751
# Distance in metres(m)
48-
AXIS_A = 6378137.0 # noqa: N806
49-
AXIS_B = 6356752.314245 # noqa: N806
50-
EQUATORIAL_RADIUS = 6378137 # noqa: N806
51-
5252
# Equation Parameters
5353
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
5454
flattening = (AXIS_A - AXIS_B) / AXIS_A

‎hashes/adler32.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
source: https://en.wikipedia.org/wiki/Adler-32
99
"""
1010

11+
MOD_ADLER = 65521
12+
1113

1214
def adler32(plain_text: str) -> int:
1315
"""
@@ -20,7 +22,6 @@ def adler32(plain_text: str) -> int:
2022
>>> adler32('go adler em all')
2123
708642122
2224
"""
23-
MOD_ADLER = 65521 # noqa: N806
2425
a = 1
2526
b = 0
2627
for plain_chr in plain_text:

‎physics/n_body_simulation.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@
1919
from matplotlib import animation
2020
from matplotlib import pyplot as plt
2121

22+
# Frame rate of the animation
23+
INTERVAL = 20
24+
25+
# Time between time steps in seconds
26+
DELTA_TIME = INTERVAL / 1000
27+
2228

2329
class Body:
2430
def __init__(
@@ -219,12 +225,6 @@ def plot(
219225
Utility function to plot how the given body-system evolves over time.
220226
No doctest provided since this function does not have a return value.
221227
"""
222-
# Frame rate of the animation
223-
INTERVAL = 20 # noqa: N806
224-
225-
# Time between time steps in seconds
226-
DELTA_TIME = INTERVAL / 1000 # noqa: N806
227-
228228
fig = plt.figure()
229229
fig.canvas.set_window_title(title)
230230
ax = plt.axes(

‎project_euler/problem_054/test_poker_hand.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,12 @@ def test_compare_random(hand, other, expected):
185185

186186

187187
def test_hand_sorted():
188-
POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] # noqa: N806
189-
list_copy = POKER_HANDS.copy()
188+
poker_hands = [PokerHand(hand) for hand in SORTED_HANDS]
189+
list_copy = poker_hands.copy()
190190
shuffle(list_copy)
191191
user_sorted = chain(sorted(list_copy))
192192
for index, hand in enumerate(user_sorted):
193-
assert hand == POKER_HANDS[index]
193+
assert hand == poker_hands[index]
194194

195195

196196
def test_custom_sort_five_high_straight():

‎project_euler/problem_064/sol1.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,13 @@ def continuous_fraction_period(n: int) -> int:
3333
"""
3434
numerator = 0.0
3535
denominator = 1.0
36-
ROOT = int(sqrt(n)) # noqa: N806
37-
integer_part = ROOT
36+
root = int(sqrt(n))
37+
integer_part = root
3838
period = 0
39-
while integer_part != 2 * ROOT:
39+
while integer_part != 2 * root:
4040
numerator = denominator * integer_part - numerator
4141
denominator = (n - numerator**2) / denominator
42-
integer_part = int((ROOT + numerator) / denominator)
42+
integer_part = int((root + numerator) / denominator)
4343
period += 1
4444
return period
4545

‎project_euler/problem_097/sol1.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ def solution(n: int = 10) -> str:
3434
"""
3535
if not isinstance(n, int) or n < 0:
3636
raise ValueError("Invalid input")
37-
MODULUS = 10**n # noqa: N806
38-
NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1 # noqa: N806
39-
return str(NUMBER % MODULUS)
37+
modulus = 10**n
38+
number = 28433 * (pow(2, 7830457, modulus)) + 1
39+
return str(number % modulus)
4040

4141

4242
if __name__ == "__main__":

‎project_euler/problem_125/sol1.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
be written as the sum of consecutive squares.
1414
"""
1515

16+
LIMIT = 10**8
17+
1618

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

‎sorts/radix_sort.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
"""
66
from __future__ import annotations
77

8+
RADIX = 10
9+
810

911
def radix_sort(list_of_ints: list[int]) -> list[int]:
1012
"""
@@ -19,7 +21,6 @@ def radix_sort(list_of_ints: list[int]) -> list[int]:
1921
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
2022
True
2123
"""
22-
RADIX = 10 # noqa: N806
2324
placement = 1
2425
max_digit = max(list_of_ints)
2526
while placement <= max_digit:

‎web_programming/fetch_quotes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@
1010

1111
import requests
1212

13+
API_ENDPOINT_URL = "https://zenquotes.io/api"
14+
1315

1416
def quote_of_the_day() -> list:
15-
API_ENDPOINT_URL = "https://zenquotes.io/api/today/" # noqa: N806
16-
return requests.get(API_ENDPOINT_URL).json()
17+
return requests.get(API_ENDPOINT_URL + "/today").json()
1718

1819

1920
def random_quotes() -> list:
20-
API_ENDPOINT_URL = "https://zenquotes.io/api/random/" # noqa: N806
21-
return requests.get(API_ENDPOINT_URL).json()
21+
return requests.get(API_ENDPOINT_URL + "/random").json()
2222

2323

2424
if __name__ == "__main__":

0 commit comments

Comments
 (0)
Please sign in to comment.