Skip to content

Commit c08fd86

Browse files
Merge branch 'TheAlgorithms:master' into main
2 parents 193e7a9 + 9e4f996 commit c08fd86

Some content is hidden

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

55 files changed

+1033
-250
lines changed

Diff for: .pre-commit-config.yaml

+4-4
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.0.284
19+
rev: v0.0.287
2020
hooks:
2121
- id: ruff
2222

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

3535
- repo: https://github.com/tox-dev/pyproject-fmt
36-
rev: "0.13.1"
36+
rev: "1.1.0"
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.13
49+
rev: v0.14
5050
hooks:
5151
- id: validate-pyproject
5252

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

Diff for: DIRECTORY.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
## Cellular Automata
7373
* [Conways Game Of Life](cellular_automata/conways_game_of_life.py)
7474
* [Game Of Life](cellular_automata/game_of_life.py)
75+
* [Langtons Ant](cellular_automata/langtons_ant.py)
7576
* [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py)
7677
* [One Dimensional](cellular_automata/one_dimensional.py)
7778
* [Wa Tor](cellular_automata/wa_tor.py)
@@ -146,7 +147,6 @@
146147
* [Convert Number To Words](conversions/convert_number_to_words.py)
147148
* [Decimal To Any](conversions/decimal_to_any.py)
148149
* [Decimal To Binary](conversions/decimal_to_binary.py)
149-
* [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py)
150150
* [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py)
151151
* [Decimal To Octal](conversions/decimal_to_octal.py)
152152
* [Energy Conversions](conversions/energy_conversions.py)
@@ -245,7 +245,6 @@
245245
* Stacks
246246
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
247247
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
248-
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
249248
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
250249
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
251250
* [Next Greater Element](data_structures/stacks/next_greater_element.py)

Diff for: arithmetic_analysis/jacobi_iteration_method.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,9 @@ def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
152152

153153
is_diagonally_dominant = True
154154

155-
for i in range(0, rows):
155+
for i in range(rows):
156156
total = 0
157-
for j in range(0, cols - 1):
157+
for j in range(cols - 1):
158158
if i == j:
159159
continue
160160
else:

Diff for: arithmetic_analysis/secant_method.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float
2020
"""
2121
x0 = lower_bound
2222
x1 = upper_bound
23-
for _ in range(0, repeats):
23+
for _ in range(repeats):
2424
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
2525
return x1
2626

Diff for: backtracking/hamiltonian_cycle.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int)
9595
return graph[path[curr_ind - 1]][path[0]] == 1
9696

9797
# Recursive Step
98-
for next_ver in range(0, len(graph)):
98+
for next_ver in range(len(graph)):
9999
if valid_connection(graph, next_ver, curr_ind, path):
100100
# Insert current vertex into path as next transition
101101
path[curr_ind] = next_ver

Diff for: backtracking/sudoku.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
4848
is found) else returns True if it is 'safe'
4949
"""
5050
for i in range(9):
51-
if grid[row][i] == n or grid[i][column] == n:
51+
if n in {grid[row][i], grid[i][column]}:
5252
return False
5353

5454
for i in range(3):

Diff for: bit_manipulation/reverse_bits.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def get_reverse_bit_string(number: int) -> str:
2020
)
2121
raise TypeError(msg)
2222
bit_string = ""
23-
for _ in range(0, 32):
23+
for _ in range(32):
2424
bit_string += str(number % 2)
2525
number = number >> 1
2626
return bit_string

Diff for: cellular_automata/langtons_ant.py

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""
2+
Langton's ant
3+
4+
@ https://en.wikipedia.org/wiki/Langton%27s_ant
5+
@ https://upload.wikimedia.org/wikipedia/commons/0/09/LangtonsAntAnimated.gif
6+
"""
7+
8+
from functools import partial
9+
10+
from matplotlib import pyplot as plt
11+
from matplotlib.animation import FuncAnimation
12+
13+
WIDTH = 80
14+
HEIGHT = 80
15+
16+
17+
class LangtonsAnt:
18+
"""
19+
Represents the main LangonsAnt algorithm.
20+
21+
>>> la = LangtonsAnt(2, 2)
22+
>>> la.board
23+
[[True, True], [True, True]]
24+
>>> la.ant_position
25+
(1, 1)
26+
"""
27+
28+
def __init__(self, width: int, height: int) -> None:
29+
# Each square is either True or False where True is white and False is black
30+
self.board = [[True] * width for _ in range(height)]
31+
self.ant_position: tuple[int, int] = (width // 2, height // 2)
32+
33+
# Initially pointing left (similar to the the wikipedia image)
34+
# (0 = 0° | 1 = 90° | 2 = 180 ° | 3 = 270°)
35+
self.ant_direction: int = 3
36+
37+
def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None:
38+
"""
39+
Performs three tasks:
40+
1. The ant turns either clockwise or anti-clockwise according to the colour
41+
of the square that it is currently on. If the square is white, the ant
42+
turns clockwise, and if the square is black the ant turns anti-clockwise
43+
2. The ant moves one square in the direction that it is currently facing
44+
3. The square the ant was previously on is inverted (White -> Black and
45+
Black -> White)
46+
47+
If display is True, the board will also be displayed on the axes
48+
49+
>>> la = LangtonsAnt(2, 2)
50+
>>> la.move_ant(None, True, 0)
51+
>>> la.board
52+
[[True, True], [True, False]]
53+
>>> la.move_ant(None, True, 0)
54+
>>> la.board
55+
[[True, False], [True, False]]
56+
"""
57+
directions = {
58+
0: (-1, 0), # 0°
59+
1: (0, 1), # 90°
60+
2: (1, 0), # 180°
61+
3: (0, -1), # 270°
62+
}
63+
x, y = self.ant_position
64+
65+
# Turn clockwise or anti-clockwise according to colour of square
66+
if self.board[x][y] is True:
67+
# The square is white so turn 90° clockwise
68+
self.ant_direction = (self.ant_direction + 1) % 4
69+
else:
70+
# The square is black so turn 90° anti-clockwise
71+
self.ant_direction = (self.ant_direction - 1) % 4
72+
73+
# Move ant
74+
move_x, move_y = directions[self.ant_direction]
75+
self.ant_position = (x + move_x, y + move_y)
76+
77+
# Flip colour of square
78+
self.board[x][y] = not self.board[x][y]
79+
80+
if display and axes:
81+
# Display the board on the axes
82+
axes.get_xaxis().set_ticks([])
83+
axes.get_yaxis().set_ticks([])
84+
axes.imshow(self.board, cmap="gray", interpolation="nearest")
85+
86+
def display(self, frames: int = 100_000) -> None:
87+
"""
88+
Displays the board without delay in a matplotlib plot
89+
to visually understand and track the ant.
90+
91+
>>> _ = LangtonsAnt(WIDTH, HEIGHT)
92+
"""
93+
fig, ax = plt.subplots()
94+
# Assign animation to a variable to prevent it from getting garbage collected
95+
self.animation = FuncAnimation(
96+
fig, partial(self.move_ant, ax, True), frames=frames, interval=1
97+
)
98+
plt.show()
99+
100+
101+
if __name__ == "__main__":
102+
import doctest
103+
104+
doctest.testmod()
105+
106+
LangtonsAnt(WIDTH, HEIGHT).display()

Diff for: ciphers/trafid_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def decrypt_message(
119119
for i in range(0, len(message) + 1, period):
120120
a, b, c = __decrypt_part(message[i : i + period], character_to_number)
121121

122-
for j in range(0, len(a)):
122+
for j in range(len(a)):
123123
decrypted_numeric.append(a[j] + b[j] + c[j])
124124

125125
for each in decrypted_numeric:

0 commit comments

Comments
 (0)