Skip to content

Commit e005f90

Browse files
Merge branch 'TheAlgorithms:master' into fix-mypy-errs-5
2 parents f167883 + c93659d commit e005f90

File tree

113 files changed

+2698
-512
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

113 files changed

+2698
-512
lines changed

Diff for: .pre-commit-config.yaml

+5-5
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/charliermarsh/ruff-pre-commit
19-
rev: v0.0.259
19+
rev: v0.0.270
2020
hooks:
2121
- id: ruff
2222

2323
- repo: https://github.com/psf/black
24-
rev: 23.1.0
24+
rev: 23.3.0
2525
hooks:
2626
- id: black
2727

@@ -33,7 +33,7 @@ repos:
3333
- tomli
3434

3535
- repo: https://github.com/tox-dev/pyproject-fmt
36-
rev: "0.9.2"
36+
rev: "0.11.2"
3737
hooks:
3838
- id: pyproject-fmt
3939

@@ -46,12 +46,12 @@ repos:
4646
pass_filenames: false
4747

4848
- repo: https://github.com/abravalheri/validate-pyproject
49-
rev: v0.12.1
49+
rev: v0.13
5050
hooks:
5151
- id: validate-pyproject
5252

5353
- repo: https://github.com/pre-commit/mirrors-mypy
54-
rev: v1.1.1
54+
rev: v1.3.0
5555
hooks:
5656
- id: mypy
5757
args:

Diff for: DIRECTORY.md

+25-2
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@
195195
* [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py)
196196
* [Disjoint Set](data_structures/disjoint_set/disjoint_set.py)
197197
* Hashing
198+
* [Bloom Filter](data_structures/hashing/bloom_filter.py)
198199
* [Double Hash](data_structures/hashing/double_hash.py)
199200
* [Hash Map](data_structures/hashing/hash_map.py)
200201
* [Hash Table](data_structures/hashing/hash_table.py)
@@ -232,6 +233,7 @@
232233
* [Double Ended Queue](data_structures/queue/double_ended_queue.py)
233234
* [Linked Queue](data_structures/queue/linked_queue.py)
234235
* [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py)
236+
* [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py)
235237
* [Queue On List](data_structures/queue/queue_on_list.py)
236238
* [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py)
237239
* Stacks
@@ -325,6 +327,7 @@
325327
* [Minimum Coin Change](dynamic_programming/minimum_coin_change.py)
326328
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
327329
* [Minimum Partition](dynamic_programming/minimum_partition.py)
330+
* [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py)
328331
* [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py)
329332
* [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py)
330333
* [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py)
@@ -337,6 +340,7 @@
337340
* [Word Break](dynamic_programming/word_break.py)
338341

339342
## Electronics
343+
* [Apparent Power](electronics/apparent_power.py)
340344
* [Builtin Voltage](electronics/builtin_voltage.py)
341345
* [Carrier Concentration](electronics/carrier_concentration.py)
342346
* [Circular Convolution](electronics/circular_convolution.py)
@@ -346,6 +350,7 @@
346350
* [Electrical Impedance](electronics/electrical_impedance.py)
347351
* [Ind Reactance](electronics/ind_reactance.py)
348352
* [Ohms Law](electronics/ohms_law.py)
353+
* [Real And Reactive Power](electronics/real_and_reactive_power.py)
349354
* [Resistor Equivalence](electronics/resistor_equivalence.py)
350355
* [Resonant Frequency](electronics/resonant_frequency.py)
351356

@@ -358,6 +363,7 @@
358363
## Financial
359364
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
360365
* [Interest](financial/interest.py)
366+
* [Present Value](financial/present_value.py)
361367
* [Price Plus Tax](financial/price_plus_tax.py)
362368

363369
## Fractals
@@ -443,6 +449,7 @@
443449
## Greedy Methods
444450
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
445451
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
452+
* [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py)
446453
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
447454

448455
## Hashes
@@ -481,6 +488,7 @@
481488
* [Astar](machine_learning/astar.py)
482489
* [Data Transformations](machine_learning/data_transformations.py)
483490
* [Decision Tree](machine_learning/decision_tree.py)
491+
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
484492
* Forecasting
485493
* [Run](machine_learning/forecasting/run.py)
486494
* [Gradient Descent](machine_learning/gradient_descent.py)
@@ -542,6 +550,7 @@
542550
* [Dodecahedron](maths/dodecahedron.py)
543551
* [Double Factorial Iterative](maths/double_factorial_iterative.py)
544552
* [Double Factorial Recursive](maths/double_factorial_recursive.py)
553+
* [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py)
545554
* [Entropy](maths/entropy.py)
546555
* [Euclidean Distance](maths/euclidean_distance.py)
547556
* [Euclidean Gcd](maths/euclidean_gcd.py)
@@ -569,6 +578,7 @@
569578
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
570579
* [Hexagonal Number](maths/hexagonal_number.py)
571580
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
581+
* [Is Int Palindrome](maths/is_int_palindrome.py)
572582
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
573583
* [Is Square Free](maths/is_square_free.py)
574584
* [Jaccard Similarity](maths/jaccard_similarity.py)
@@ -598,10 +608,12 @@
598608
* [Newton Raphson](maths/newton_raphson.py)
599609
* [Number Of Digits](maths/number_of_digits.py)
600610
* [Numerical Integration](maths/numerical_integration.py)
611+
* [Odd Sieve](maths/odd_sieve.py)
601612
* [Perfect Cube](maths/perfect_cube.py)
602613
* [Perfect Number](maths/perfect_number.py)
603614
* [Perfect Square](maths/perfect_square.py)
604615
* [Persistence](maths/persistence.py)
616+
* [Pi Generator](maths/pi_generator.py)
605617
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
606618
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
607619
* [Pollard Rho](maths/pollard_rho.py)
@@ -623,6 +635,7 @@
623635
* [Radians](maths/radians.py)
624636
* [Radix2 Fft](maths/radix2_fft.py)
625637
* [Relu](maths/relu.py)
638+
* [Remove Digit](maths/remove_digit.py)
626639
* [Runge Kutta](maths/runge_kutta.py)
627640
* [Segmented Sieve](maths/segmented_sieve.py)
628641
* Series
@@ -648,6 +661,7 @@
648661
* [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py)
649662
* [Sumset](maths/sumset.py)
650663
* [Sylvester Sequence](maths/sylvester_sequence.py)
664+
* [Tanh](maths/tanh.py)
651665
* [Test Prime Check](maths/test_prime_check.py)
652666
* [Trapezoidal Rule](maths/trapezoidal_rule.py)
653667
* [Triplet Sum](maths/triplet_sum.py)
@@ -684,6 +698,8 @@
684698

685699
## Neural Network
686700
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
701+
* Activation Functions
702+
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
687703
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
688704
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
689705
* [Input Data](neural_network/input_data.py)
@@ -700,12 +716,15 @@
700716
* [Gauss Easter](other/gauss_easter.py)
701717
* [Graham Scan](other/graham_scan.py)
702718
* [Greedy](other/greedy.py)
719+
* [Guess The Number Search](other/guess_the_number_search.py)
720+
* [H Index](other/h_index.py)
703721
* [Least Recently Used](other/least_recently_used.py)
704722
* [Lfu Cache](other/lfu_cache.py)
705723
* [Linear Congruential Generator](other/linear_congruential_generator.py)
706724
* [Lru Cache](other/lru_cache.py)
707725
* [Magicdiamondpattern](other/magicdiamondpattern.py)
708726
* [Maximum Subarray](other/maximum_subarray.py)
727+
* [Maximum Subsequence](other/maximum_subsequence.py)
709728
* [Nested Brackets](other/nested_brackets.py)
710729
* [Password](other/password.py)
711730
* [Quine](other/quine.py)
@@ -922,6 +941,8 @@
922941
* [Sol1](project_euler/problem_077/sol1.py)
923942
* Problem 078
924943
* [Sol1](project_euler/problem_078/sol1.py)
944+
* Problem 079
945+
* [Sol1](project_euler/problem_079/sol1.py)
925946
* Problem 080
926947
* [Sol1](project_euler/problem_080/sol1.py)
927948
* Problem 081
@@ -1033,6 +1054,7 @@
10331054
* [Q Fourier Transform](quantum/q_fourier_transform.py)
10341055
* [Q Full Adder](quantum/q_full_adder.py)
10351056
* [Quantum Entanglement](quantum/quantum_entanglement.py)
1057+
* [Quantum Random](quantum/quantum_random.py)
10361058
* [Quantum Teleportation](quantum/quantum_teleportation.py)
10371059
* [Ripple Adder Classic](quantum/ripple_adder_classic.py)
10381060
* [Single Qubit Measure](quantum/single_qubit_measure.py)
@@ -1066,6 +1088,7 @@
10661088

10671089
## Sorts
10681090
* [Bead Sort](sorts/bead_sort.py)
1091+
* [Binary Insertion Sort](sorts/binary_insertion_sort.py)
10691092
* [Bitonic Sort](sorts/bitonic_sort.py)
10701093
* [Bogo Sort](sorts/bogo_sort.py)
10711094
* [Bubble Sort](sorts/bubble_sort.py)
@@ -1134,7 +1157,6 @@
11341157
* [Indian Phone Validator](strings/indian_phone_validator.py)
11351158
* [Is Contains Unique Chars](strings/is_contains_unique_chars.py)
11361159
* [Is Isogram](strings/is_isogram.py)
1137-
* [Is Palindrome](strings/is_palindrome.py)
11381160
* [Is Pangram](strings/is_pangram.py)
11391161
* [Is Spain National Id](strings/is_spain_national_id.py)
11401162
* [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py)
@@ -1156,7 +1178,9 @@
11561178
* [Reverse Words](strings/reverse_words.py)
11571179
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
11581180
* [Split](strings/split.py)
1181+
* [String Switch Case](strings/string_switch_case.py)
11591182
* [Text Justification](strings/text_justification.py)
1183+
* [Top K Frequent Words](strings/top_k_frequent_words.py)
11601184
* [Upper](strings/upper.py)
11611185
* [Wave](strings/wave.py)
11621186
* [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py)
@@ -1176,7 +1200,6 @@
11761200
* [Daily Horoscope](web_programming/daily_horoscope.py)
11771201
* [Download Images From Google Query](web_programming/download_images_from_google_query.py)
11781202
* [Emails From Url](web_programming/emails_from_url.py)
1179-
* [Fetch Anime And Play](web_programming/fetch_anime_and_play.py)
11801203
* [Fetch Bbc News](web_programming/fetch_bbc_news.py)
11811204
* [Fetch Github Info](web_programming/fetch_github_info.py)
11821205
* [Fetch Jobs](web_programming/fetch_jobs.py)

Diff for: arithmetic_analysis/jacobi_iteration_method.py

+18-12
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ def jacobi_iteration_method(
4949
>>> constant = np.array([[2], [-6]])
5050
>>> init_val = [0.5, -0.5, -0.5]
5151
>>> iterations = 3
52-
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
52+
>>> jacobi_iteration_method(
53+
... coefficient, constant, init_val, iterations
54+
... ) # doctest: +NORMALIZE_WHITESPACE
5355
Traceback (most recent call last):
5456
...
5557
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
@@ -59,7 +61,9 @@ def jacobi_iteration_method(
5961
>>> constant = np.array([[2], [-6], [-4]])
6062
>>> init_val = [0.5, -0.5]
6163
>>> iterations = 3
62-
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
64+
>>> jacobi_iteration_method(
65+
... coefficient, constant, init_val, iterations
66+
... ) # doctest: +NORMALIZE_WHITESPACE
6367
Traceback (most recent call last):
6468
...
6569
ValueError: Number of initial values must be equal to number of rows in coefficient
@@ -79,24 +83,26 @@ def jacobi_iteration_method(
7983
rows2, cols2 = constant_matrix.shape
8084

8185
if rows1 != cols1:
82-
raise ValueError(
83-
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
84-
)
86+
msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
87+
raise ValueError(msg)
8588

8689
if cols2 != 1:
87-
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}")
90+
msg = f"Constant matrix must be nx1 but received {rows2}x{cols2}"
91+
raise ValueError(msg)
8892

8993
if rows1 != rows2:
90-
raise ValueError(
91-
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but
92-
received {rows1}x{cols1} and {rows2}x{cols2}"""
94+
msg = (
95+
"Coefficient and constant matrices dimensions must be nxn and nx1 but "
96+
f"received {rows1}x{cols1} and {rows2}x{cols2}"
9397
)
98+
raise ValueError(msg)
9499

95100
if len(init_val) != rows1:
96-
raise ValueError(
97-
f"""Number of initial values must be equal to number of rows in coefficient
98-
matrix but received {len(init_val)} and {rows1}"""
101+
msg = (
102+
"Number of initial values must be equal to number of rows in coefficient "
103+
f"matrix but received {len(init_val)} and {rows1}"
99104
)
105+
raise ValueError(msg)
100106

101107
if iterations <= 0:
102108
raise ValueError("Iterations must be at least 1")

Diff for: arithmetic_analysis/lu_decomposition.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,11 @@ def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray
8080
# Ensure that table is a square array
8181
rows, columns = np.shape(table)
8282
if rows != columns:
83-
raise ValueError(
84-
f"'table' has to be of square shaped array but got a "
83+
msg = (
84+
"'table' has to be of square shaped array but got a "
8585
f"{rows}x{columns} array:\n{table}"
8686
)
87+
raise ValueError(msg)
8788

8889
lower = np.zeros((rows, columns))
8990
upper = np.zeros((rows, columns))

Diff for: audio_filters/iir_filter.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,18 @@ def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None
5050
a_coeffs = [1.0, *a_coeffs]
5151

5252
if len(a_coeffs) != self.order + 1:
53-
raise ValueError(
54-
f"Expected a_coeffs to have {self.order + 1} elements for {self.order}"
55-
f"-order filter, got {len(a_coeffs)}"
53+
msg = (
54+
f"Expected a_coeffs to have {self.order + 1} elements "
55+
f"for {self.order}-order filter, got {len(a_coeffs)}"
5656
)
57+
raise ValueError(msg)
5758

5859
if len(b_coeffs) != self.order + 1:
59-
raise ValueError(
60-
f"Expected b_coeffs to have {self.order + 1} elements for {self.order}"
61-
f"-order filter, got {len(a_coeffs)}"
60+
msg = (
61+
f"Expected b_coeffs to have {self.order + 1} elements "
62+
f"for {self.order}-order filter, got {len(a_coeffs)}"
6263
)
64+
raise ValueError(msg)
6365

6466
self.a_coeffs = a_coeffs
6567
self.b_coeffs = b_coeffs

Diff for: backtracking/knight_tour.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ def open_knight_tour(n: int) -> list[list[int]]:
9191
return board
9292
board[i][j] = 0
9393

94-
raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}")
94+
msg = f"Open Kight Tour cannot be performed on a board of size {n}"
95+
raise ValueError(msg)
9596

9697

9798
if __name__ == "__main__":

Diff for: bit_manipulation/reverse_bits.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ def get_reverse_bit_string(number: int) -> str:
1414
TypeError: operation can not be conducted on a object of type str
1515
"""
1616
if not isinstance(number, int):
17-
raise TypeError(
17+
msg = (
1818
"operation can not be conducted on a object of type "
1919
f"{type(number).__name__}"
2020
)
21+
raise TypeError(msg)
2122
bit_string = ""
2223
for _ in range(0, 32):
2324
bit_string += str(number % 2)

Diff for: boolean_algebra/and_gate.py

+2
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ def test_and_gate() -> None:
4343

4444

4545
if __name__ == "__main__":
46+
test_and_gate()
47+
print(and_gate(1, 0))
4648
print(and_gate(0, 0))
4749
print(and_gate(0, 1))
4850
print(and_gate(1, 1))

Diff for: cellular_automata/game_of_life.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from matplotlib import pyplot as plt
3535
from matplotlib.colors import ListedColormap
3636

37-
usage_doc = "Usage of script: script_nama <size_of_canvas:int>"
37+
usage_doc = "Usage of script: script_name <size_of_canvas:int>"
3838

3939
choice = [0] * 100 + [1] * 10
4040
random.shuffle(choice)

Diff for: ciphers/base64.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,8 @@ def base64_encode(data: bytes) -> bytes:
3434
"""
3535
# Make sure the supplied data is a bytes-like object
3636
if not isinstance(data, bytes):
37-
raise TypeError(
38-
f"a bytes-like object is required, not '{data.__class__.__name__}'"
39-
)
37+
msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
38+
raise TypeError(msg)
4039

4140
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
4241

@@ -88,10 +87,11 @@ def base64_decode(encoded_data: str) -> bytes:
8887
"""
8988
# Make sure encoded_data is either a string or a bytes-like object
9089
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
91-
raise TypeError(
92-
"argument should be a bytes-like object or ASCII string, not "
93-
f"'{encoded_data.__class__.__name__}'"
90+
msg = (
91+
"argument should be a bytes-like object or ASCII string, "
92+
f"not '{encoded_data.__class__.__name__}'"
9493
)
94+
raise TypeError(msg)
9595

9696
# In case encoded_data is a bytes-like object, make sure it contains only
9797
# ASCII characters so we convert it to a string object

Diff for: ciphers/beaufort_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from string import ascii_uppercase
66

77
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
8-
dict2 = {i: char for i, char in enumerate(ascii_uppercase)}
8+
dict2 = dict(enumerate(ascii_uppercase))
99

1010

1111
# This function generates the key in

0 commit comments

Comments
 (0)