Skip to content

Commit 77fb26d

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents 84e314e + 77bbe58 commit 77fb26d

File tree

69 files changed

+724
-312
lines changed

Some content is hidden

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

69 files changed

+724
-312
lines changed

.pre-commit-config.yaml

Lines changed: 5 additions & 4 deletions
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.5
19+
rev: v0.6.5
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.3"
3333
hooks:
3434
- id: pyproject-fmt
3535

@@ -42,15 +42,16 @@ repos:
4242
pass_filenames: false
4343

4444
- repo: https://github.com/abravalheri/validate-pyproject
45-
rev: v0.18
45+
rev: v0.19
4646
hooks:
4747
- id: validate-pyproject
4848

4949
- repo: https://github.com/pre-commit/mirrors-mypy
50-
rev: v1.10.0
50+
rev: v1.11.2
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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,15 @@
243243
* [Min Heap](data_structures/heap/min_heap.py)
244244
* [Randomized Heap](data_structures/heap/randomized_heap.py)
245245
* [Skew Heap](data_structures/heap/skew_heap.py)
246+
* Kd Tree
247+
* [Build Kdtree](data_structures/kd_tree/build_kdtree.py)
248+
* Example
249+
* [Example Usage](data_structures/kd_tree/example/example_usage.py)
250+
* [Hypercube Points](data_structures/kd_tree/example/hypercube_points.py)
251+
* [Kd Node](data_structures/kd_tree/kd_node.py)
252+
* [Nearest Neighbour Search](data_structures/kd_tree/nearest_neighbour_search.py)
253+
* Tests
254+
* [Test Kdtree](data_structures/kd_tree/tests/test_kdtree.py)
246255
* Linked List
247256
* [Circular Linked List](data_structures/linked_list/circular_linked_list.py)
248257
* [Deque Doubly](data_structures/linked_list/deque_doubly.py)
@@ -540,8 +549,7 @@
540549
* [Lu Decomposition](linear_algebra/lu_decomposition.py)
541550
* Src
542551
* [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)
552+
* [Gaussian Elimination Pivoting](linear_algebra/src/gaussian_elimination_pivoting.py)
545553
* [Lib](linear_algebra/src/lib.py)
546554
* [Polynom For Points](linear_algebra/src/polynom_for_points.py)
547555
* [Power Iteration](linear_algebra/src/power_iteration.py)
@@ -863,6 +871,7 @@
863871
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
864872
* [Photoelectric Effect](physics/photoelectric_effect.py)
865873
* [Potential Energy](physics/potential_energy.py)
874+
* [Rainfall Intensity](physics/rainfall_intensity.py)
866875
* [Reynolds Number](physics/reynolds_number.py)
867876
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
868877
* [Shear Stress](physics/shear_stress.py)
@@ -1259,6 +1268,7 @@
12591268
* [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py)
12601269
* [Capitalize](strings/capitalize.py)
12611270
* [Check Anagrams](strings/check_anagrams.py)
1271+
* [Count Vowels](strings/count_vowels.py)
12621272
* [Credit Card Validator](strings/credit_card_validator.py)
12631273
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
12641274
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)

backtracking/knight_tour.py

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

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

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

Lines changed: 3 additions & 3 deletions
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/number_of_possible_binary_trees.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ def binomial_coefficient(n: int, k: int) -> int:
3131
"""
3232
result = 1 # To kept the Calculated Value
3333
# Since C(n, k) = C(n, n-k)
34-
if k > (n - k):
35-
k = n - k
34+
k = min(k, n - k)
3635
# Calculate C(n,k)
3736
for i in range(k):
3837
result *= n - i

data_structures/binary_tree/red_black_tree.py

Lines changed: 9 additions & 28 deletions
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:
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from data_structures.kd_tree.kd_node import KDNode
2+
3+
4+
def build_kdtree(points: list[list[float]], depth: int = 0) -> KDNode | None:
5+
"""
6+
Builds a KD-Tree from a list of points.
7+
8+
Args:
9+
points: The list of points to build the KD-Tree from.
10+
depth: The current depth in the tree
11+
(used to determine axis for splitting).
12+
13+
Returns:
14+
The root node of the KD-Tree,
15+
or None if no points are provided.
16+
"""
17+
if not points:
18+
return None
19+
20+
k = len(points[0]) # Dimensionality of the points
21+
axis = depth % k
22+
23+
# Sort point list and choose median as pivot element
24+
points.sort(key=lambda point: point[axis])
25+
median_idx = len(points) // 2
26+
27+
# Create node and construct subtrees
28+
left_points = points[:median_idx]
29+
right_points = points[median_idx + 1 :]
30+
31+
return KDNode(
32+
point=points[median_idx],
33+
left=build_kdtree(left_points, depth + 1),
34+
right=build_kdtree(right_points, depth + 1),
35+
)

0 commit comments

Comments
 (0)