Skip to content

Commit d0c90f9

Browse files
committed
refactor: Move constants outside of variable scope
1 parent 553624f commit d0c90f9

17 files changed

+108
-89
lines changed

ciphers/bifid.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@
1010
import numpy as np
1111

1212

13+
SQUARE = [
14+
["a", "b", "c", "d", "e"],
15+
["f", "g", "h", "i", "k"],
16+
["l", "m", "n", "o", "p"],
17+
["q", "r", "s", "t", "u"],
18+
["v", "w", "x", "y", "z"],
19+
]
20+
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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2+
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3+
14
def decrypt(message: str) -> None:
25
"""
36
>>> decrypt('TMDETUX PMDVU')
@@ -28,7 +31,6 @@ 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
3234
for key in range(len(LETTERS)):
3335
translated = ""
3436
for symbol in message:

ciphers/polybius.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,18 @@
99
import numpy as np
1010

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+
20+
1221
class PolybiusCipher:
1322
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-
]
23+
2124
self.SQUARE = np.array(SQUARE)
2225

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

compression/peak_signal_to_noise_ratio.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
import numpy as np
1313

1414

15+
PIXEL_MAX = 255.0
16+
1517
def psnr(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+
psnr = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
23+
return psnr
2224

2325

2426
def main() -> None:

conversions/binary_to_hexadecimal.py

Lines changed: 20 additions & 19 deletions
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

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
"""Convert a positive Decimal Number to Any Other Representation"""
22

33

4+
# fmt: off
5+
ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', # noqa: E501
6+
'16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L',
7+
'22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R',
8+
'28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X',
9+
'34': 'Y', '35': 'Z'}
10+
# fmt: on
11+
12+
413
def decimal_to_any(num: int, base: int) -> str:
514
"""
615
Convert a positive integer to another base as str.
@@ -65,13 +74,6 @@ def decimal_to_any(num: int, base: int) -> str:
6574
raise ValueError("base must be >= 2")
6675
if base > 36:
6776
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
7577
new_value = ""
7678
mod = 0
7779
div = 0

conversions/roman_numerals.py

Lines changed: 17 additions & 15 deletions
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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
from math import asin, atan, cos, radians, sin, sqrt, tan
22

33

4+
AXIS_A = 6378137.0
5+
AXIS_B = 6356752.314245
6+
RADIUS = 6378137
7+
48
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
59
"""
610
Calculate great circle distance between two points in a sphere,
@@ -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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
from .haversine_distance import haversine_distance
44

55

6+
AXIS_A = 6378137.0
7+
AXIS_B = 6356752.314245
8+
EQUATORIAL_RADIUS = 6378137
9+
10+
611
def lamberts_ellipsoidal_distance(
712
lat1: float, lon1: float, lat2: float, lon2: float
813
) -> float:
@@ -45,10 +50,6 @@ def lamberts_ellipsoidal_distance(
4550

4651
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
4752
# 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-
5253
# Equation Parameters
5354
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
5455
flattening = (AXIS_A - AXIS_B) / AXIS_A

hashes/adler32.py

Lines changed: 2 additions & 1 deletion
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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@
2020
from matplotlib import pyplot as plt
2121

2222

23+
# Frame rate of the animation
24+
INTERVAL = 20
25+
26+
# Time between time steps in seconds
27+
DELTA_TIME = INTERVAL / 1000
28+
29+
2330
class Body:
2431
def __init__(
2532
self,
@@ -219,12 +226,6 @@ def plot(
219226
Utility function to plot how the given body-system evolves over time.
220227
No doctest provided since this function does not have a return value.
221228
"""
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-
228229
fig = plt.figure()
229230
fig.canvas.set_window_title(title)
230231
ax = plt.axes(

project_euler/problem_054/test_poker_hand.py

Lines changed: 3 additions & 3 deletions
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

Lines changed: 4 additions & 4 deletions
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

Lines changed: 3 additions & 3 deletions
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
be written as the sum of consecutive squares.
1414
"""
1515

16+
LIMIT = 10**8
1617

1718
def is_palindrome(n: int) -> bool:
1819
"""
@@ -35,7 +36,6 @@ def solution() -> int:
3536
Returns the sum of all numbers less than 1e8 that are both palindromic and
3637
can be written as the sum of consecutive squares.
3738
"""
38-
LIMIT = 10**8 # noqa: N806
3939
answer = set()
4040
first_square = 1
4141
sum_squares = 5

sorts/radix_sort.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
from __future__ import annotations
77

88

9+
RADIX = 10
10+
11+
912
def radix_sort(list_of_ints: list[int]) -> list[int]:
1013
"""
1114
Examples:
@@ -19,7 +22,6 @@ def radix_sort(list_of_ints: list[int]) -> list[int]:
1922
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
2023
True
2124
"""
22-
RADIX = 10 # noqa: N806
2325
placement = 1
2426
max_digit = max(list_of_ints)
2527
while placement <= max_digit:

web_programming/fetch_quotes.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212

1313

1414
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()
15+
api_endpoint_url = "https://zenquotes.io/api/today/"
16+
return requests.get(api_endpoint_url).json()
1717

1818

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

2323

2424
if __name__ == "__main__":

0 commit comments

Comments
 (0)