Skip to content

Commit ebbdc71

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent a09138b commit ebbdc71

File tree

2 files changed

+55
-21
lines changed

2 files changed

+55
-21
lines changed

Diff for: graphs/ant_colony_optimization_algorithms.py

+27-10
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,21 @@
1313
7: [6, 2],
1414
}
1515

16+
1617
def euclidean_distance(city1: list[int], city2: list[int]) -> float:
1718
"""
1819
Calculate the Euclidean distance between two cities (points).
1920
"""
2021
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
2122

23+
2224
def initialize_pheromone_matrix(size: int) -> list[list[float]]:
2325
"""
2426
Initialize the pheromone matrix with 1.0 values.
2527
"""
2628
return [[1.0 for _ in range(size)] for _ in range(size)]
2729

30+
2831
def compute_distance_matrix(cities: dict[int, list[int]]) -> list[list[float]]:
2932
"""
3033
Precompute the distance between all cities and store them in a matrix.
@@ -38,13 +41,14 @@ def compute_distance_matrix(cities: dict[int, list[int]]) -> list[list[float]]:
3841
dist_matrix[j][i] = dist
3942
return dist_matrix
4043

44+
4145
def select_next_city(
4246
current_city: int,
4347
unvisited: list[int],
4448
pheromone: list[list[float]],
4549
distances: list[list[float]],
4650
alpha: float,
47-
beta: float
51+
beta: float,
4852
) -> int:
4953
"""
5054
Select the next city to visit based on pheromone levels and distances.
@@ -62,14 +66,15 @@ def select_next_city(
6266
# Randomly select next city based on the probabilities
6367
return random.choices(unvisited, weights=probabilities)[0]
6468

69+
6570
def update_pheromones(
6671
pheromone: list[list[float]],
6772
ants_paths: list[list[int]],
6873
distances: list[list[float]],
6974
q: float,
7075
evaporation_rate: float,
7176
best_path: list[int],
72-
best_distance: float
77+
best_distance: float,
7378
) -> tuple[list[list[float]], list[int], float]:
7479
"""
7580
Update pheromone levels on the paths chosen by ants.
@@ -79,11 +84,13 @@ def update_pheromones(
7984
# Evaporate pheromones
8085
for i in range(size):
8186
for j in range(size):
82-
pheromone[i][j] *= (1 - evaporation_rate)
87+
pheromone[i][j] *= 1 - evaporation_rate
8388

8489
# Update pheromones based on ants' paths
8590
for path in ants_paths:
86-
total_distance = sum(distances[path[i]][path[i + 1]] for i in range(len(path) - 1))
91+
total_distance = sum(
92+
distances[path[i]][path[i + 1]] for i in range(len(path) - 1)
93+
)
8794
pheromone_deposit = q / total_distance
8895

8996
for i in range(len(path) - 1):
@@ -97,28 +104,29 @@ def update_pheromones(
97104

98105
return pheromone, best_path, best_distance
99106

107+
100108
def ant_colony_optimization(
101109
cities: dict[int, list[int]],
102110
ants_num: int,
103111
iterations: int,
104112
alpha: float,
105113
beta: float,
106114
evaporation_rate: float,
107-
q: float
115+
q: float,
108116
) -> tuple[list[int], float]:
109117
"""
110118
Solve the TSP using Ant Colony Optimization (ACO).
111119
"""
112120
cities_num = len(cities)
113121
if cities_num == 0:
114-
return [], float('inf') # No cities to visit
122+
return [], float("inf") # No cities to visit
115123

116124
# Initialize pheromone and distance matrices
117125
pheromone = initialize_pheromone_matrix(cities_num)
118126
distances = compute_distance_matrix(cities)
119127

120128
best_path = []
121-
best_distance = float('inf')
129+
best_distance = float("inf")
122130

123131
for _ in range(iterations):
124132
all_paths = []
@@ -129,7 +137,9 @@ def ant_colony_optimization(
129137
# Construct path for the ant
130138
current_city = 0
131139
while unvisited:
132-
next_city = select_next_city(current_city, unvisited, pheromone, distances, alpha, beta)
140+
next_city = select_next_city(
141+
current_city, unvisited, pheromone, distances, alpha, beta
142+
)
133143
path.append(next_city)
134144
unvisited.remove(next_city)
135145
current_city = next_city
@@ -139,11 +149,18 @@ def ant_colony_optimization(
139149

140150
# Update pheromones and track the best path found
141151
pheromone, best_path, best_distance = update_pheromones(
142-
pheromone, all_paths, distances, q, evaporation_rate, best_path, best_distance
152+
pheromone,
153+
all_paths,
154+
distances,
155+
q,
156+
evaporation_rate,
157+
best_path,
158+
best_distance,
143159
)
144160

145161
return best_path, best_distance
146162

163+
147164
if __name__ == "__main__":
148165
# Example usage
149166
best_path, best_distance = ant_colony_optimization(
@@ -153,7 +170,7 @@ def ant_colony_optimization(
153170
alpha=1.0,
154171
beta=5.0,
155172
evaporation_rate=0.7,
156-
q=10
173+
q=10,
157174
)
158175

159176
print(f"Best path: {best_path}")

Diff for: strings/aho_corasick.py

+28-11
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@
22
from collections import deque
33
from typing import List, Dict
44

5+
56
class State:
67
"""Represents a state in the Aho-Corasick automaton."""
8+
79
def __init__(self, value: str):
810
self.value = value
911
self.next_states: List[int] = []
1012
self.fail_state: int = 0
1113
self.output: List[str] = []
1214

15+
1316
class Automaton:
1417
def __init__(self, keywords: List[str]):
1518
self.adlist: List[State] = [State("")] # Initial root state
@@ -44,37 +47,50 @@ def set_fail_transitions(self) -> None:
4447
for node in self.adlist[0].next_states:
4548
q.append(node)
4649
self.adlist[node].fail_state = 0
47-
50+
4851
while q:
4952
r = q.popleft()
5053
for child in self.adlist[r].next_states:
5154
q.append(child)
5255
state = self.adlist[r].fail_state
53-
while (self.find_state_by_character(state, self.adlist[child].value) is None and state != 0):
56+
while (
57+
self.find_state_by_character(state, self.adlist[child].value)
58+
is None
59+
and state != 0
60+
):
5461
state = self.adlist[state].fail_state
55-
56-
fail_state = self.find_state_by_character(state, self.adlist[child].value)
57-
self.adlist[child].fail_state = fail_state if fail_state is not None else 0
58-
self.adlist[child].output.extend(self.adlist[self.adlist[child].fail_state].output)
62+
63+
fail_state = self.find_state_by_character(
64+
state, self.adlist[child].value
65+
)
66+
self.adlist[child].fail_state = (
67+
fail_state if fail_state is not None else 0
68+
)
69+
self.adlist[child].output.extend(
70+
self.adlist[self.adlist[child].fail_state].output
71+
)
5972

6073
def search_in(self, string: str) -> Dict[str, List[int]]:
6174
"""
6275
Search for keywords in the given string.
6376
6477
Returns a dictionary with keywords and the list of their occurrences.
65-
78+
6679
Example:
6780
>>> A = Automaton(["what", "hat", "ver", "er"])
6881
>>> A.search_in("whatever, err ... , wherever")
6982
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
7083
"""
7184
result: Dict[str, List[int]] = {}
7285
current_state = 0
73-
86+
7487
for i in range(len(string)):
75-
while self.find_state_by_character(current_state, string[i]) is None and current_state != 0:
88+
while (
89+
self.find_state_by_character(current_state, string[i]) is None
90+
and current_state != 0
91+
):
7692
current_state = self.adlist[current_state].fail_state
77-
93+
7894
next_state = self.find_state_by_character(current_state, string[i])
7995
if next_state is None:
8096
current_state = 0
@@ -84,10 +100,11 @@ def search_in(self, string: str) -> Dict[str, List[int]]:
84100
if key not in result:
85101
result[key] = []
86102
result[key].append(i - len(key) + 1)
87-
103+
88104
return result
89105

90106

91107
if __name__ == "__main__":
92108
import doctest
109+
93110
doctest.testmod()

0 commit comments

Comments
 (0)