Skip to content

Commit e6790b5

Browse files
committed
2 parents b2e30e7 + 4841828 commit e6790b5

Some content is hidden

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

46 files changed

+189
-207
lines changed

.pre-commit-config.yaml

+4-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/astral-sh/ruff-pre-commit
19-
rev: v0.4.7
19+
rev: v0.5.7
2020
hooks:
2121
- id: ruff
2222
- id: ruff-format
@@ -29,7 +29,7 @@ repos:
2929
- tomli
3030

3131
- repo: https://github.com/tox-dev/pyproject-fmt
32-
rev: "2.1.3"
32+
rev: "2.2.1"
3333
hooks:
3434
- id: pyproject-fmt
3535

@@ -47,10 +47,11 @@ repos:
4747
- id: validate-pyproject
4848

4949
- repo: https://github.com/pre-commit/mirrors-mypy
50-
rev: v1.10.0
50+
rev: v1.11.1
5151
hooks:
5252
- id: mypy
5353
args:
54+
- --explicit-package-bases
5455
- --ignore-missing-imports
5556
- --install-types # See mirrors-mypy README.md
5657
- --non-interactive

DIRECTORY.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -540,8 +540,7 @@
540540
* [Lu Decomposition](linear_algebra/lu_decomposition.py)
541541
* Src
542542
* [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py)
543-
* Gaussian Elimination Pivoting
544-
* [Gaussian Elimination Pivoting](linear_algebra/src/gaussian_elimination_pivoting/gaussian_elimination_pivoting.py)
543+
* [Gaussian Elimination Pivoting](linear_algebra/src/gaussian_elimination_pivoting.py)
545544
* [Lib](linear_algebra/src/lib.py)
546545
* [Polynom For Points](linear_algebra/src/polynom_for_points.py)
547546
* [Power Iteration](linear_algebra/src/power_iteration.py)
@@ -863,6 +862,7 @@
863862
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
864863
* [Photoelectric Effect](physics/photoelectric_effect.py)
865864
* [Potential Energy](physics/potential_energy.py)
865+
* [Rainfall Intensity](physics/rainfall_intensity.py)
866866
* [Reynolds Number](physics/reynolds_number.py)
867867
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
868868
* [Shear Stress](physics/shear_stress.py)
@@ -1259,6 +1259,7 @@
12591259
* [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py)
12601260
* [Capitalize](strings/capitalize.py)
12611261
* [Check Anagrams](strings/check_anagrams.py)
1262+
* [Count Vowels](strings/count_vowels.py)
12621263
* [Credit Card Validator](strings/credit_card_validator.py)
12631264
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
12641265
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)

backtracking/knight_tour.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
2424
]
2525
permissible_positions = []
2626

27-
for position in positions:
28-
y_test, x_test = position
27+
for inner_position in positions:
28+
y_test, x_test = inner_position
2929
if 0 <= y_test < n and 0 <= x_test < n:
30-
permissible_positions.append(position)
30+
permissible_positions.append(inner_position)
3131

3232
return permissible_positions
3333

computer_vision/haralick_descriptors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def transform(
141141

142142
center_x, center_y = (x // 2 for x in kernel.shape)
143143

144-
# Use padded image when applying convolotion
144+
# Use padded image when applying convolution
145145
# to not go out of bounds of the original the image
146146
transformed = np.zeros(image.shape, dtype=np.uint8)
147147
padded = np.pad(image, 1, "constant", constant_values=constant)

conversions/weight_conversion.py

+6
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,12 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
297297
1.660540199e-23
298298
>>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2)
299299
1.999999998903455
300+
>>> weight_conversion("slug", "kilogram", 1)
301+
Traceback (most recent call last):
302+
...
303+
ValueError: Invalid 'from_type' or 'to_type' value: 'slug', 'kilogram'
304+
Supported values are: kilogram, gram, milligram, metric-ton, long-ton, short-ton, \
305+
pound, stone, ounce, carrat, atomic-mass-unit
300306
"""
301307
if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
302308
msg = (

data_structures/binary_tree/is_sorted.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@ def is_sorted(self) -> bool:
8080
"""
8181
if self.left and (self.data < self.left.data or not self.left.is_sorted):
8282
return False
83-
if self.right and (self.data > self.right.data or not self.right.is_sorted):
84-
return False
85-
return True
83+
return not (
84+
self.right and (self.data > self.right.data or not self.right.is_sorted)
85+
)
8686

8787

8888
if __name__ == "__main__":

data_structures/binary_tree/red_black_tree.py

+9-28
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
"""
2-
psf/black : true
3-
ruff : passed
4-
"""
5-
61
from __future__ import annotations
72

83
from collections.abc import Iterator
@@ -321,9 +316,7 @@ def check_coloring(self) -> bool:
321316
return False
322317
if self.left and not self.left.check_coloring():
323318
return False
324-
if self.right and not self.right.check_coloring():
325-
return False
326-
return True
319+
return not (self.right and not self.right.check_coloring())
327320

328321
def black_height(self) -> int | None:
329322
"""Returns the number of black nodes from this node to the
@@ -561,9 +554,7 @@ def test_rotations() -> bool:
561554
right_rot.right.right = RedBlackTree(10, parent=right_rot.right)
562555
right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right)
563556
right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right)
564-
if tree != right_rot:
565-
return False
566-
return True
557+
return tree == right_rot
567558

568559

569560
def test_insertion_speed() -> bool:
@@ -606,13 +597,11 @@ def test_insert_and_search() -> bool:
606597
tree.insert(12)
607598
tree.insert(10)
608599
tree.insert(11)
609-
if 5 in tree or -6 in tree or -10 in tree or 13 in tree:
600+
if any(i in tree for i in (5, -6, -10, 13)):
610601
# Found something not in there
611602
return False
612-
if not (11 in tree and 12 in tree and -8 in tree and 0 in tree):
613-
# Didn't find something in there
614-
return False
615-
return True
603+
# Find all these things in there
604+
return all(i in tree for i in (11, 12, -8, 0))
616605

617606

618607
def test_insert_delete() -> bool:
@@ -634,9 +623,7 @@ def test_insert_delete() -> bool:
634623
tree = tree.remove(9)
635624
if not tree.check_color_properties():
636625
return False
637-
if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]:
638-
return False
639-
return True
626+
return list(tree.inorder_traverse()) == [-8, 0, 4, 8, 10, 11, 12]
640627

641628

642629
def test_floor_ceil() -> bool:
@@ -664,9 +651,7 @@ def test_min_max() -> bool:
664651
tree.insert(24)
665652
tree.insert(20)
666653
tree.insert(22)
667-
if tree.get_max() != 22 or tree.get_min() != -16:
668-
return False
669-
return True
654+
return not (tree.get_max() != 22 or tree.get_min() != -16)
670655

671656

672657
def test_tree_traversal() -> bool:
@@ -682,9 +667,7 @@ def test_tree_traversal() -> bool:
682667
return False
683668
if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
684669
return False
685-
if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
686-
return False
687-
return True
670+
return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0]
688671

689672

690673
def test_tree_chaining() -> bool:
@@ -695,9 +678,7 @@ def test_tree_chaining() -> bool:
695678
return False
696679
if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
697680
return False
698-
if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
699-
return False
700-
return True
681+
return list(tree.postorder_traverse()) == [-16, 8, 20, 24, 22, 16, 0]
701682

702683

703684
def print_results(msg: str, passes: bool) -> None:

graphs/graph_adjacency_matrix.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,11 @@ def remove_vertex(self, vertex: T) -> None:
156156
self.vertex_to_index.pop(vertex)
157157

158158
# decrement indices for vertices shifted by the deleted vertex in the adj matrix
159-
for vertex in self.vertex_to_index:
160-
if self.vertex_to_index[vertex] >= start_index:
161-
self.vertex_to_index[vertex] = self.vertex_to_index[vertex] - 1
159+
for inner_vertex in self.vertex_to_index:
160+
if self.vertex_to_index[inner_vertex] >= start_index:
161+
self.vertex_to_index[inner_vertex] = (
162+
self.vertex_to_index[inner_vertex] - 1
163+
)
162164

163165
def contains_vertex(self, vertex: T) -> bool:
164166
"""

graphs/multi_heuristic_astar.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def key(start: TPos, i: int, goal: TPos, g_function: dict[TPos, float]):
7979

8080

8181
def do_something(back_pointer, goal, start):
82-
grid = np.chararray((n, n))
82+
grid = np.char.chararray((n, n))
8383
for i in range(n):
8484
for j in range(n):
8585
grid[i][j] = "*"
@@ -123,9 +123,7 @@ def do_something(back_pointer, goal, start):
123123
def valid(p: TPos):
124124
if p[0] < 0 or p[0] > n - 1:
125125
return False
126-
if p[1] < 0 or p[1] > n - 1:
127-
return False
128-
return True
126+
return not (p[1] < 0 or p[1] > n - 1)
129127

130128

131129
def expand_state(

graphs/strongly_connected_components.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def find_components(
3838
reversed_graph: dict[int, list[int]], vert: int, visited: list[bool]
3939
) -> list[int]:
4040
"""
41-
Use depth first search to find strongliy connected
41+
Use depth first search to find strongly connected
4242
vertices. Now graph is reversed
4343
>>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False])
4444
[0, 1, 2]

graphs/tarjans_scc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,4 @@ def create_graph(n: int, edges: list[tuple[int, int]]) -> list[list[int]]:
103103
edges = list(zip(source, target))
104104
g = create_graph(n_vertices, edges)
105105

106-
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
106+
assert tarjan(g) == [[5], [6], [4], [3, 2, 1, 0]]

hashes/md5.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ def reformat_hex(i: int) -> bytes:
8282

8383
hex_rep = format(i, "08x")[-8:]
8484
little_endian_hex = b""
85-
for i in [3, 2, 1, 0]:
86-
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8")
85+
for j in [3, 2, 1, 0]:
86+
little_endian_hex += hex_rep[2 * j : 2 * j + 2].encode("utf-8")
8787
return little_endian_hex
8888

8989

+13-20
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,5 @@
11
import numpy as np
22

3-
matrix = np.array(
4-
[
5-
[5.0, -5.0, -3.0, 4.0, -11.0],
6-
[1.0, -4.0, 6.0, -4.0, -10.0],
7-
[-2.0, -5.0, 4.0, -5.0, -12.0],
8-
[-3.0, -3.0, 5.0, -5.0, 8.0],
9-
],
10-
dtype=float,
11-
)
12-
133

144
def solve_linear_system(matrix: np.ndarray) -> np.ndarray:
155
"""
@@ -87,15 +77,18 @@ def solve_linear_system(matrix: np.ndarray) -> np.ndarray:
8777

8878
if __name__ == "__main__":
8979
from doctest import testmod
90-
from pathlib import Path
9180

9281
testmod()
93-
file_path = Path(__file__).parent / "matrix.txt"
94-
try:
95-
matrix = np.loadtxt(file_path)
96-
except FileNotFoundError:
97-
print(f"Error: {file_path} not found. Using default matrix instead.")
98-
99-
# Example usage:
100-
print(f"Matrix:\n{matrix}")
101-
print(f"{solve_linear_system(matrix) = }")
82+
83+
example_matrix = np.array(
84+
[
85+
[5.0, -5.0, -3.0, 4.0, -11.0],
86+
[1.0, -4.0, 6.0, -4.0, -10.0],
87+
[-2.0, -5.0, 4.0, -5.0, -12.0],
88+
[-3.0, -3.0, 5.0, -5.0, 8.0],
89+
],
90+
dtype=float,
91+
)
92+
93+
print(f"Matrix:\n{example_matrix}")
94+
print(f"{solve_linear_system(example_matrix) = }")

linear_algebra/src/gaussian_elimination_pivoting/matrix.txt

-4
This file was deleted.

maths/numerical_analysis/integration_by_simpson_approx.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
55
Purpose : You have one function f(x) which takes float integer and returns
66
float you have to integrate the function in limits a to b.
7-
The approximation proposed by Thomas Simpsons in 1743 is one way to calculate
7+
The approximation proposed by Thomas Simpson in 1743 is one way to calculate
88
integration.
99
1010
( read article : https://cp-algorithms.com/num_methods/simpson-integration.html )

maths/points_are_collinear_3d.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,9 @@ def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d:
7676

7777
def is_zero_vector(vector: Vector3d, accuracy: int) -> bool:
7878
"""
79-
Check if vector is equal to (0, 0, 0) of not.
79+
Check if vector is equal to (0, 0, 0) or not.
8080
81-
Sine the algorithm is very accurate, we will never get a zero vector,
81+
Since the algorithm is very accurate, we will never get a zero vector,
8282
so we need to round the vector axis,
8383
because we want a result that is either True or False.
8484
In other applications, we can return a float that represents the collinearity ratio.
@@ -97,9 +97,9 @@ def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> boo
9797
"""
9898
Check if three points are collinear or not.
9999
100-
1- Create tow vectors AB and AC.
101-
2- Get the cross vector of the tow vectors.
102-
3- Calcolate the length of the cross vector.
100+
1- Create two vectors AB and AC.
101+
2- Get the cross vector of the two vectors.
102+
3- Calculate the length of the cross vector.
103103
4- If the length is zero then the points are collinear, else they are not.
104104
105105
The use of the accuracy parameter is explained in is_zero_vector docstring.

maths/radix2_fft.py

-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ def __dft(self, which):
8484
# Corner case
8585
if len(dft) <= 1:
8686
return dft[0]
87-
#
8887
next_ncol = self.c_max_length // 2
8988
while next_ncol > 0:
9089
new_dft = [[] for i in range(next_ncol)]

neural_network/convolution_neural_network.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
33
Name - - CNN - Convolution Neural Network For Photo Recognizing
4-
Goal - - Recognize Handing Writing Word Photo
4+
Goal - - Recognize Handwriting Word Photo
55
Detail: Total 5 layers neural network
66
* Convolution layer
77
* Pooling layer
@@ -135,7 +135,7 @@ def convolute(self, data, convs, w_convs, thre_convs, conv_step):
135135
)
136136
data_featuremap.append(featuremap)
137137

138-
# expanding the data slice to One dimenssion
138+
# expanding the data slice to one dimension
139139
focus1_list = []
140140
for each_focus in data_focus:
141141
focus1_list.extend(self.Expand_Mat(each_focus))
@@ -304,7 +304,7 @@ def draw_error():
304304
plt.grid(True, alpha=0.5)
305305
plt.show()
306306

307-
print("------------------Training Complished---------------------")
307+
print("------------------Training Complete---------------------")
308308
print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}"))
309309
if draw_e:
310310
draw_error()
@@ -353,5 +353,5 @@ def convolution(self, data):
353353

354354
if __name__ == "__main__":
355355
"""
356-
I will put the example on other file
356+
I will put the example in another file
357357
"""

project_euler/problem_034/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
#

project_euler/problem_035/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
#

project_euler/problem_037/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
#

0 commit comments

Comments
 (0)