mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-03-13 09:50:19 +08:00
Add pep8-naming to pre-commit hooks and fixes incorrect naming conventions (#7062)
* ci(pre-commit): Add pep8-naming to `pre-commit` hooks (#7038) * refactor: Fix naming conventions (#7038) * Update arithmetic_analysis/lu_decomposition.py Co-authored-by: Christian Clauss <cclauss@me.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor(lu_decomposition): Replace `NDArray` with `ArrayLike` (#7038) * chore: Fix naming conventions in doctests (#7038) * fix: Temporarily disable project euler problem 104 (#7069) * chore: Fix naming conventions in doctests (#7038) Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
# Finding Articulation Points in Undirected Graph
|
||||
def computeAP(l): # noqa: E741
|
||||
def compute_ap(l): # noqa: E741
|
||||
n = len(l)
|
||||
outEdgeCount = 0
|
||||
out_edge_count = 0
|
||||
low = [0] * n
|
||||
visited = [False] * n
|
||||
isArt = [False] * n
|
||||
is_art = [False] * n
|
||||
|
||||
def dfs(root, at, parent, outEdgeCount):
|
||||
def dfs(root, at, parent, out_edge_count):
|
||||
if parent == root:
|
||||
outEdgeCount += 1
|
||||
out_edge_count += 1
|
||||
visited[at] = True
|
||||
low[at] = at
|
||||
|
||||
@@ -16,27 +16,27 @@ def computeAP(l): # noqa: E741
|
||||
if to == parent:
|
||||
pass
|
||||
elif not visited[to]:
|
||||
outEdgeCount = dfs(root, to, at, outEdgeCount)
|
||||
out_edge_count = dfs(root, to, at, out_edge_count)
|
||||
low[at] = min(low[at], low[to])
|
||||
|
||||
# AP found via bridge
|
||||
if at < low[to]:
|
||||
isArt[at] = True
|
||||
is_art[at] = True
|
||||
# AP found via cycle
|
||||
if at == low[to]:
|
||||
isArt[at] = True
|
||||
is_art[at] = True
|
||||
else:
|
||||
low[at] = min(low[at], to)
|
||||
return outEdgeCount
|
||||
return out_edge_count
|
||||
|
||||
for i in range(n):
|
||||
if not visited[i]:
|
||||
outEdgeCount = 0
|
||||
outEdgeCount = dfs(i, i, -1, outEdgeCount)
|
||||
isArt[i] = outEdgeCount > 1
|
||||
out_edge_count = 0
|
||||
out_edge_count = dfs(i, i, -1, out_edge_count)
|
||||
is_art[i] = out_edge_count > 1
|
||||
|
||||
for x in range(len(isArt)):
|
||||
if isArt[x] is True:
|
||||
for x in range(len(is_art)):
|
||||
if is_art[x] is True:
|
||||
print(x)
|
||||
|
||||
|
||||
@@ -52,4 +52,4 @@ data = {
|
||||
7: [6, 8],
|
||||
8: [5, 7],
|
||||
}
|
||||
computeAP(data)
|
||||
compute_ap(data)
|
||||
|
||||
@@ -76,20 +76,20 @@ if __name__ == "__main__":
|
||||
"""
|
||||
|
||||
|
||||
def dfs(G, s):
|
||||
vis, S = {s}, [s]
|
||||
def dfs(g, s):
|
||||
vis, _s = {s}, [s]
|
||||
print(s)
|
||||
while S:
|
||||
while _s:
|
||||
flag = 0
|
||||
for i in G[S[-1]]:
|
||||
for i in g[_s[-1]]:
|
||||
if i not in vis:
|
||||
S.append(i)
|
||||
_s.append(i)
|
||||
vis.add(i)
|
||||
flag = 1
|
||||
print(i)
|
||||
break
|
||||
if not flag:
|
||||
S.pop()
|
||||
_s.pop()
|
||||
|
||||
|
||||
"""
|
||||
@@ -103,15 +103,15 @@ def dfs(G, s):
|
||||
"""
|
||||
|
||||
|
||||
def bfs(G, s):
|
||||
vis, Q = {s}, deque([s])
|
||||
def bfs(g, s):
|
||||
vis, q = {s}, deque([s])
|
||||
print(s)
|
||||
while Q:
|
||||
u = Q.popleft()
|
||||
for v in G[u]:
|
||||
while q:
|
||||
u = q.popleft()
|
||||
for v in g[u]:
|
||||
if v not in vis:
|
||||
vis.add(v)
|
||||
Q.append(v)
|
||||
q.append(v)
|
||||
print(v)
|
||||
|
||||
|
||||
@@ -127,10 +127,10 @@ def bfs(G, s):
|
||||
"""
|
||||
|
||||
|
||||
def dijk(G, s):
|
||||
def dijk(g, s):
|
||||
dist, known, path = {s: 0}, set(), {s: 0}
|
||||
while True:
|
||||
if len(known) == len(G) - 1:
|
||||
if len(known) == len(g) - 1:
|
||||
break
|
||||
mini = 100000
|
||||
for i in dist:
|
||||
@@ -138,7 +138,7 @@ def dijk(G, s):
|
||||
mini = dist[i]
|
||||
u = i
|
||||
known.add(u)
|
||||
for v in G[u]:
|
||||
for v in g[u]:
|
||||
if v[0] not in known:
|
||||
if dist[u] + v[1] < dist.get(v[0], 100000):
|
||||
dist[v[0]] = dist[u] + v[1]
|
||||
@@ -155,27 +155,27 @@ def dijk(G, s):
|
||||
"""
|
||||
|
||||
|
||||
def topo(G, ind=None, Q=None):
|
||||
if Q is None:
|
||||
Q = [1]
|
||||
def topo(g, ind=None, q=None):
|
||||
if q is None:
|
||||
q = [1]
|
||||
if ind is None:
|
||||
ind = [0] * (len(G) + 1) # SInce oth Index is ignored
|
||||
for u in G:
|
||||
for v in G[u]:
|
||||
ind = [0] * (len(g) + 1) # SInce oth Index is ignored
|
||||
for u in g:
|
||||
for v in g[u]:
|
||||
ind[v] += 1
|
||||
Q = deque()
|
||||
for i in G:
|
||||
q = deque()
|
||||
for i in g:
|
||||
if ind[i] == 0:
|
||||
Q.append(i)
|
||||
if len(Q) == 0:
|
||||
q.append(i)
|
||||
if len(q) == 0:
|
||||
return
|
||||
v = Q.popleft()
|
||||
v = q.popleft()
|
||||
print(v)
|
||||
for w in G[v]:
|
||||
for w in g[v]:
|
||||
ind[w] -= 1
|
||||
if ind[w] == 0:
|
||||
Q.append(w)
|
||||
topo(G, ind, Q)
|
||||
q.append(w)
|
||||
topo(g, ind, q)
|
||||
|
||||
|
||||
"""
|
||||
@@ -206,9 +206,9 @@ def adjm():
|
||||
"""
|
||||
|
||||
|
||||
def floy(A_and_n):
|
||||
(A, n) = A_and_n
|
||||
dist = list(A)
|
||||
def floy(a_and_n):
|
||||
(a, n) = a_and_n
|
||||
dist = list(a)
|
||||
path = [[0] * n for i in range(n)]
|
||||
for k in range(n):
|
||||
for i in range(n):
|
||||
@@ -231,10 +231,10 @@ def floy(A_and_n):
|
||||
"""
|
||||
|
||||
|
||||
def prim(G, s):
|
||||
def prim(g, s):
|
||||
dist, known, path = {s: 0}, set(), {s: 0}
|
||||
while True:
|
||||
if len(known) == len(G) - 1:
|
||||
if len(known) == len(g) - 1:
|
||||
break
|
||||
mini = 100000
|
||||
for i in dist:
|
||||
@@ -242,7 +242,7 @@ def prim(G, s):
|
||||
mini = dist[i]
|
||||
u = i
|
||||
known.add(u)
|
||||
for v in G[u]:
|
||||
for v in g[u]:
|
||||
if v[0] not in known:
|
||||
if v[1] < dist.get(v[0], 100000):
|
||||
dist[v[0]] = v[1]
|
||||
@@ -279,16 +279,16 @@ def edglist():
|
||||
"""
|
||||
|
||||
|
||||
def krusk(E_and_n):
|
||||
def krusk(e_and_n):
|
||||
# Sort edges on the basis of distance
|
||||
(E, n) = E_and_n
|
||||
E.sort(reverse=True, key=lambda x: x[2])
|
||||
(e, n) = e_and_n
|
||||
e.sort(reverse=True, key=lambda x: x[2])
|
||||
s = [{i} for i in range(1, n + 1)]
|
||||
while True:
|
||||
if len(s) == 1:
|
||||
break
|
||||
print(s)
|
||||
x = E.pop()
|
||||
x = e.pop()
|
||||
for i in range(len(s)):
|
||||
if x[0] in s[i]:
|
||||
break
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
from queue import Queue
|
||||
|
||||
|
||||
def checkBipartite(graph):
|
||||
def check_bipartite(graph):
|
||||
queue = Queue()
|
||||
visited = [False] * len(graph)
|
||||
color = [-1] * len(graph)
|
||||
@@ -45,4 +45,4 @@ def checkBipartite(graph):
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Adjacency List of graph
|
||||
print(checkBipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
|
||||
print(check_bipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))
|
||||
|
||||
@@ -103,14 +103,14 @@ G3 = {
|
||||
"G": [["F", 1]],
|
||||
}
|
||||
|
||||
shortDistance = dijkstra(G, "E", "C")
|
||||
print(shortDistance) # E -- 3 --> F -- 3 --> C == 6
|
||||
short_distance = dijkstra(G, "E", "C")
|
||||
print(short_distance) # E -- 3 --> F -- 3 --> C == 6
|
||||
|
||||
shortDistance = dijkstra(G2, "E", "F")
|
||||
print(shortDistance) # E -- 3 --> F == 3
|
||||
short_distance = dijkstra(G2, "E", "F")
|
||||
print(short_distance) # E -- 3 --> F == 3
|
||||
|
||||
shortDistance = dijkstra(G3, "E", "F")
|
||||
print(shortDistance) # E -- 2 --> G -- 1 --> F == 3
|
||||
short_distance = dijkstra(G3, "E", "F")
|
||||
print(short_distance) # E -- 2 --> G -- 1 --> F == 3
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
def printDist(dist, V):
|
||||
def print_dist(dist, v):
|
||||
print("\nVertex Distance")
|
||||
for i in range(V):
|
||||
for i in range(v):
|
||||
if dist[i] != float("inf"):
|
||||
print(i, "\t", int(dist[i]), end="\t")
|
||||
else:
|
||||
@@ -8,26 +8,26 @@ def printDist(dist, V):
|
||||
print()
|
||||
|
||||
|
||||
def minDist(mdist, vset, V):
|
||||
minVal = float("inf")
|
||||
minInd = -1
|
||||
for i in range(V):
|
||||
if (not vset[i]) and mdist[i] < minVal:
|
||||
minInd = i
|
||||
minVal = mdist[i]
|
||||
return minInd
|
||||
def min_dist(mdist, vset, v):
|
||||
min_val = float("inf")
|
||||
min_ind = -1
|
||||
for i in range(v):
|
||||
if (not vset[i]) and mdist[i] < min_val:
|
||||
min_ind = i
|
||||
min_val = mdist[i]
|
||||
return min_ind
|
||||
|
||||
|
||||
def Dijkstra(graph, V, src):
|
||||
mdist = [float("inf") for i in range(V)]
|
||||
vset = [False for i in range(V)]
|
||||
def dijkstra(graph, v, src):
|
||||
mdist = [float("inf") for i in range(v)]
|
||||
vset = [False for i in range(v)]
|
||||
mdist[src] = 0.0
|
||||
|
||||
for i in range(V - 1):
|
||||
u = minDist(mdist, vset, V)
|
||||
for i in range(v - 1):
|
||||
u = min_dist(mdist, vset, v)
|
||||
vset[u] = True
|
||||
|
||||
for v in range(V):
|
||||
for v in range(v):
|
||||
if (
|
||||
(not vset[v])
|
||||
and graph[u][v] != float("inf")
|
||||
@@ -35,7 +35,7 @@ def Dijkstra(graph, V, src):
|
||||
):
|
||||
mdist[v] = mdist[u] + graph[u][v]
|
||||
|
||||
printDist(mdist, V)
|
||||
print_dist(mdist, v)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -55,4 +55,4 @@ if __name__ == "__main__":
|
||||
graph[src][dst] = weight
|
||||
|
||||
gsrc = int(input("\nEnter shortest path source:").strip())
|
||||
Dijkstra(graph, V, gsrc)
|
||||
dijkstra(graph, V, gsrc)
|
||||
|
||||
@@ -15,7 +15,7 @@ class PriorityQueue:
|
||||
self.array = []
|
||||
self.pos = {} # To store the pos of node in array
|
||||
|
||||
def isEmpty(self):
|
||||
def is_empty(self):
|
||||
return self.cur_size == 0
|
||||
|
||||
def min_heapify(self, idx):
|
||||
@@ -110,24 +110,24 @@ class Graph:
|
||||
self.par = [-1] * self.num_nodes
|
||||
# src is the source node
|
||||
self.dist[src] = 0
|
||||
Q = PriorityQueue()
|
||||
Q.insert((0, src)) # (dist from src, node)
|
||||
q = PriorityQueue()
|
||||
q.insert((0, src)) # (dist from src, node)
|
||||
for u in self.adjList.keys():
|
||||
if u != src:
|
||||
self.dist[u] = sys.maxsize # Infinity
|
||||
self.par[u] = -1
|
||||
|
||||
while not Q.isEmpty():
|
||||
u = Q.extract_min() # Returns node with the min dist from source
|
||||
while not q.is_empty():
|
||||
u = q.extract_min() # Returns node with the min dist from source
|
||||
# Update the distance of all the neighbours of u and
|
||||
# if their prev dist was INFINITY then push them in Q
|
||||
for v, w in self.adjList[u]:
|
||||
new_dist = self.dist[u] + w
|
||||
if self.dist[v] > new_dist:
|
||||
if self.dist[v] == sys.maxsize:
|
||||
Q.insert((new_dist, v))
|
||||
q.insert((new_dist, v))
|
||||
else:
|
||||
Q.decrease_key((self.dist[v], v), new_dist)
|
||||
q.decrease_key((self.dist[v], v), new_dist)
|
||||
self.dist[v] = new_dist
|
||||
self.par[v] = u
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
class FlowNetwork:
|
||||
def __init__(self, graph, sources, sinks):
|
||||
self.sourceIndex = None
|
||||
self.sinkIndex = None
|
||||
self.source_index = None
|
||||
self.sink_index = None
|
||||
self.graph = graph
|
||||
|
||||
self._normalizeGraph(sources, sinks)
|
||||
self.verticesCount = len(graph)
|
||||
self.maximumFlowAlgorithm = None
|
||||
self._normalize_graph(sources, sinks)
|
||||
self.vertices_count = len(graph)
|
||||
self.maximum_flow_algorithm = None
|
||||
|
||||
# make only one source and one sink
|
||||
def _normalizeGraph(self, sources, sinks):
|
||||
def _normalize_graph(self, sources, sinks):
|
||||
if sources is int:
|
||||
sources = [sources]
|
||||
if sinks is int:
|
||||
@@ -18,54 +18,54 @@ class FlowNetwork:
|
||||
if len(sources) == 0 or len(sinks) == 0:
|
||||
return
|
||||
|
||||
self.sourceIndex = sources[0]
|
||||
self.sinkIndex = sinks[0]
|
||||
self.source_index = sources[0]
|
||||
self.sink_index = sinks[0]
|
||||
|
||||
# make fake vertex if there are more
|
||||
# than one source or sink
|
||||
if len(sources) > 1 or len(sinks) > 1:
|
||||
maxInputFlow = 0
|
||||
max_input_flow = 0
|
||||
for i in sources:
|
||||
maxInputFlow += sum(self.graph[i])
|
||||
max_input_flow += sum(self.graph[i])
|
||||
|
||||
size = len(self.graph) + 1
|
||||
for room in self.graph:
|
||||
room.insert(0, 0)
|
||||
self.graph.insert(0, [0] * size)
|
||||
for i in sources:
|
||||
self.graph[0][i + 1] = maxInputFlow
|
||||
self.sourceIndex = 0
|
||||
self.graph[0][i + 1] = max_input_flow
|
||||
self.source_index = 0
|
||||
|
||||
size = len(self.graph) + 1
|
||||
for room in self.graph:
|
||||
room.append(0)
|
||||
self.graph.append([0] * size)
|
||||
for i in sinks:
|
||||
self.graph[i + 1][size - 1] = maxInputFlow
|
||||
self.sinkIndex = size - 1
|
||||
self.graph[i + 1][size - 1] = max_input_flow
|
||||
self.sink_index = size - 1
|
||||
|
||||
def findMaximumFlow(self):
|
||||
if self.maximumFlowAlgorithm is None:
|
||||
def find_maximum_flow(self):
|
||||
if self.maximum_flow_algorithm is None:
|
||||
raise Exception("You need to set maximum flow algorithm before.")
|
||||
if self.sourceIndex is None or self.sinkIndex is None:
|
||||
if self.source_index is None or self.sink_index is None:
|
||||
return 0
|
||||
|
||||
self.maximumFlowAlgorithm.execute()
|
||||
return self.maximumFlowAlgorithm.getMaximumFlow()
|
||||
self.maximum_flow_algorithm.execute()
|
||||
return self.maximum_flow_algorithm.getMaximumFlow()
|
||||
|
||||
def setMaximumFlowAlgorithm(self, Algorithm):
|
||||
self.maximumFlowAlgorithm = Algorithm(self)
|
||||
def set_maximum_flow_algorithm(self, algorithm):
|
||||
self.maximum_flow_algorithm = algorithm(self)
|
||||
|
||||
|
||||
class FlowNetworkAlgorithmExecutor:
|
||||
def __init__(self, flowNetwork):
|
||||
self.flowNetwork = flowNetwork
|
||||
self.verticesCount = flowNetwork.verticesCount
|
||||
self.sourceIndex = flowNetwork.sourceIndex
|
||||
self.sinkIndex = flowNetwork.sinkIndex
|
||||
def __init__(self, flow_network):
|
||||
self.flow_network = flow_network
|
||||
self.verticies_count = flow_network.verticesCount
|
||||
self.source_index = flow_network.sourceIndex
|
||||
self.sink_index = flow_network.sinkIndex
|
||||
# it's just a reference, so you shouldn't change
|
||||
# it in your algorithms, use deep copy before doing that
|
||||
self.graph = flowNetwork.graph
|
||||
self.graph = flow_network.graph
|
||||
self.executed = False
|
||||
|
||||
def execute(self):
|
||||
@@ -79,95 +79,96 @@ class FlowNetworkAlgorithmExecutor:
|
||||
|
||||
|
||||
class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor):
|
||||
def __init__(self, flowNetwork):
|
||||
super().__init__(flowNetwork)
|
||||
def __init__(self, flow_network):
|
||||
super().__init__(flow_network)
|
||||
# use this to save your result
|
||||
self.maximumFlow = -1
|
||||
self.maximum_flow = -1
|
||||
|
||||
def getMaximumFlow(self):
|
||||
def get_maximum_flow(self):
|
||||
if not self.executed:
|
||||
raise Exception("You should execute algorithm before using its result!")
|
||||
|
||||
return self.maximumFlow
|
||||
return self.maximum_flow
|
||||
|
||||
|
||||
class PushRelabelExecutor(MaximumFlowAlgorithmExecutor):
|
||||
def __init__(self, flowNetwork):
|
||||
super().__init__(flowNetwork)
|
||||
def __init__(self, flow_network):
|
||||
super().__init__(flow_network)
|
||||
|
||||
self.preflow = [[0] * self.verticesCount for i in range(self.verticesCount)]
|
||||
self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)]
|
||||
|
||||
self.heights = [0] * self.verticesCount
|
||||
self.excesses = [0] * self.verticesCount
|
||||
self.heights = [0] * self.verticies_count
|
||||
self.excesses = [0] * self.verticies_count
|
||||
|
||||
def _algorithm(self):
|
||||
self.heights[self.sourceIndex] = self.verticesCount
|
||||
self.heights[self.source_index] = self.verticies_count
|
||||
|
||||
# push some substance to graph
|
||||
for nextVertexIndex, bandwidth in enumerate(self.graph[self.sourceIndex]):
|
||||
self.preflow[self.sourceIndex][nextVertexIndex] += bandwidth
|
||||
self.preflow[nextVertexIndex][self.sourceIndex] -= bandwidth
|
||||
self.excesses[nextVertexIndex] += bandwidth
|
||||
for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]):
|
||||
self.preflow[self.source_index][nextvertex_index] += bandwidth
|
||||
self.preflow[nextvertex_index][self.source_index] -= bandwidth
|
||||
self.excesses[nextvertex_index] += bandwidth
|
||||
|
||||
# Relabel-to-front selection rule
|
||||
verticesList = [
|
||||
vertices_list = [
|
||||
i
|
||||
for i in range(self.verticesCount)
|
||||
if i != self.sourceIndex and i != self.sinkIndex
|
||||
for i in range(self.verticies_count)
|
||||
if i != self.source_index and i != self.sink_index
|
||||
]
|
||||
|
||||
# move through list
|
||||
i = 0
|
||||
while i < len(verticesList):
|
||||
vertexIndex = verticesList[i]
|
||||
previousHeight = self.heights[vertexIndex]
|
||||
self.processVertex(vertexIndex)
|
||||
if self.heights[vertexIndex] > previousHeight:
|
||||
while i < len(vertices_list):
|
||||
vertex_index = vertices_list[i]
|
||||
previous_height = self.heights[vertex_index]
|
||||
self.process_vertex(vertex_index)
|
||||
if self.heights[vertex_index] > previous_height:
|
||||
# if it was relabeled, swap elements
|
||||
# and start from 0 index
|
||||
verticesList.insert(0, verticesList.pop(i))
|
||||
vertices_list.insert(0, vertices_list.pop(i))
|
||||
i = 0
|
||||
else:
|
||||
i += 1
|
||||
|
||||
self.maximumFlow = sum(self.preflow[self.sourceIndex])
|
||||
self.maximum_flow = sum(self.preflow[self.source_index])
|
||||
|
||||
def processVertex(self, vertexIndex):
|
||||
while self.excesses[vertexIndex] > 0:
|
||||
for neighbourIndex in range(self.verticesCount):
|
||||
def process_vertex(self, vertex_index):
|
||||
while self.excesses[vertex_index] > 0:
|
||||
for neighbour_index in range(self.verticies_count):
|
||||
# if it's neighbour and current vertex is higher
|
||||
if (
|
||||
self.graph[vertexIndex][neighbourIndex]
|
||||
- self.preflow[vertexIndex][neighbourIndex]
|
||||
self.graph[vertex_index][neighbour_index]
|
||||
- self.preflow[vertex_index][neighbour_index]
|
||||
> 0
|
||||
and self.heights[vertexIndex] > self.heights[neighbourIndex]
|
||||
and self.heights[vertex_index] > self.heights[neighbour_index]
|
||||
):
|
||||
self.push(vertexIndex, neighbourIndex)
|
||||
self.push(vertex_index, neighbour_index)
|
||||
|
||||
self.relabel(vertexIndex)
|
||||
self.relabel(vertex_index)
|
||||
|
||||
def push(self, fromIndex, toIndex):
|
||||
preflowDelta = min(
|
||||
self.excesses[fromIndex],
|
||||
self.graph[fromIndex][toIndex] - self.preflow[fromIndex][toIndex],
|
||||
def push(self, from_index, to_index):
|
||||
preflow_delta = min(
|
||||
self.excesses[from_index],
|
||||
self.graph[from_index][to_index] - self.preflow[from_index][to_index],
|
||||
)
|
||||
self.preflow[fromIndex][toIndex] += preflowDelta
|
||||
self.preflow[toIndex][fromIndex] -= preflowDelta
|
||||
self.excesses[fromIndex] -= preflowDelta
|
||||
self.excesses[toIndex] += preflowDelta
|
||||
self.preflow[from_index][to_index] += preflow_delta
|
||||
self.preflow[to_index][from_index] -= preflow_delta
|
||||
self.excesses[from_index] -= preflow_delta
|
||||
self.excesses[to_index] += preflow_delta
|
||||
|
||||
def relabel(self, vertexIndex):
|
||||
minHeight = None
|
||||
for toIndex in range(self.verticesCount):
|
||||
def relabel(self, vertex_index):
|
||||
min_height = None
|
||||
for to_index in range(self.verticies_count):
|
||||
if (
|
||||
self.graph[vertexIndex][toIndex] - self.preflow[vertexIndex][toIndex]
|
||||
self.graph[vertex_index][to_index]
|
||||
- self.preflow[vertex_index][to_index]
|
||||
> 0
|
||||
):
|
||||
if minHeight is None or self.heights[toIndex] < minHeight:
|
||||
minHeight = self.heights[toIndex]
|
||||
if min_height is None or self.heights[to_index] < min_height:
|
||||
min_height = self.heights[to_index]
|
||||
|
||||
if minHeight is not None:
|
||||
self.heights[vertexIndex] = minHeight + 1
|
||||
if min_height is not None:
|
||||
self.heights[vertex_index] = min_height + 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -184,10 +185,10 @@ if __name__ == "__main__":
|
||||
graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]
|
||||
|
||||
# prepare our network
|
||||
flowNetwork = FlowNetwork(graph, entrances, exits)
|
||||
flow_network = FlowNetwork(graph, entrances, exits)
|
||||
# set algorithm
|
||||
flowNetwork.setMaximumFlowAlgorithm(PushRelabelExecutor)
|
||||
flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
|
||||
# and calculate
|
||||
maximumFlow = flowNetwork.findMaximumFlow()
|
||||
maximum_flow = flow_network.find_maximum_flow()
|
||||
|
||||
print(f"maximum flow is {maximumFlow}")
|
||||
print(f"maximum flow is {maximum_flow}")
|
||||
|
||||
@@ -50,21 +50,21 @@ def check_euler(graph, max_node):
|
||||
|
||||
|
||||
def main():
|
||||
G1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
|
||||
G2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
|
||||
G3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
|
||||
G4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
|
||||
G5 = {
|
||||
g1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}
|
||||
g2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}
|
||||
g3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}
|
||||
g4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
|
||||
g5 = {
|
||||
1: [],
|
||||
2: []
|
||||
# all degree is zero
|
||||
}
|
||||
max_node = 10
|
||||
check_euler(G1, max_node)
|
||||
check_euler(G2, max_node)
|
||||
check_euler(G3, max_node)
|
||||
check_euler(G4, max_node)
|
||||
check_euler(G5, max_node)
|
||||
check_euler(g1, max_node)
|
||||
check_euler(g2, max_node)
|
||||
check_euler(g3, max_node)
|
||||
check_euler(g4, max_node)
|
||||
check_euler(g5, max_node)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -151,16 +151,16 @@ def create_edge(nodes, graph, cluster, c1):
|
||||
|
||||
|
||||
def construct_graph(cluster, nodes):
|
||||
X = cluster[max(cluster.keys())]
|
||||
x = cluster[max(cluster.keys())]
|
||||
cluster[max(cluster.keys()) + 1] = "Header"
|
||||
graph = {}
|
||||
for i in X:
|
||||
for i in x:
|
||||
if tuple(["Header"]) in graph:
|
||||
graph[tuple(["Header"])].append(X[i])
|
||||
graph[tuple(["Header"])].append(x[i])
|
||||
else:
|
||||
graph[tuple(["Header"])] = [X[i]]
|
||||
for i in X:
|
||||
graph[tuple(X[i])] = [["Header"]]
|
||||
graph[tuple(["Header"])] = [x[i]]
|
||||
for i in x:
|
||||
graph[tuple(x[i])] = [["Header"]]
|
||||
i = 1
|
||||
while i < max(cluster) - 1:
|
||||
create_edge(nodes, graph, cluster, i)
|
||||
@@ -168,7 +168,7 @@ def construct_graph(cluster, nodes):
|
||||
return graph
|
||||
|
||||
|
||||
def myDFS(graph, start, end, path=None):
|
||||
def my_dfs(graph, start, end, path=None):
|
||||
"""
|
||||
find different DFS walk from given node to Header node
|
||||
"""
|
||||
@@ -177,7 +177,7 @@ def myDFS(graph, start, end, path=None):
|
||||
paths.append(path)
|
||||
for node in graph[start]:
|
||||
if tuple(node) not in path:
|
||||
myDFS(graph, tuple(node), end, path)
|
||||
my_dfs(graph, tuple(node), end, path)
|
||||
|
||||
|
||||
def find_freq_subgraph_given_support(s, cluster, graph):
|
||||
@@ -186,23 +186,23 @@ def find_freq_subgraph_given_support(s, cluster, graph):
|
||||
"""
|
||||
k = int(s / 100 * (len(cluster) - 1))
|
||||
for i in cluster[k].keys():
|
||||
myDFS(graph, tuple(cluster[k][i]), tuple(["Header"]))
|
||||
my_dfs(graph, tuple(cluster[k][i]), tuple(["Header"]))
|
||||
|
||||
|
||||
def freq_subgraphs_edge_list(paths):
|
||||
"""
|
||||
returns Edge list for frequent subgraphs
|
||||
"""
|
||||
freq_sub_EL = []
|
||||
freq_sub_el = []
|
||||
for edges in paths:
|
||||
EL = []
|
||||
el = []
|
||||
for j in range(len(edges) - 1):
|
||||
temp = list(edges[j])
|
||||
for e in temp:
|
||||
edge = (e[0], e[1])
|
||||
EL.append(edge)
|
||||
freq_sub_EL.append(EL)
|
||||
return freq_sub_EL
|
||||
el.append(edge)
|
||||
freq_sub_el.append(el)
|
||||
return freq_sub_el
|
||||
|
||||
|
||||
def preprocess(edge_array):
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
|
||||
def longestDistance(graph):
|
||||
def longest_distance(graph):
|
||||
indegree = [0] * len(graph)
|
||||
queue = []
|
||||
longDist = [1] * len(graph)
|
||||
long_dist = [1] * len(graph)
|
||||
|
||||
for key, values in graph.items():
|
||||
for i in values:
|
||||
@@ -17,15 +17,15 @@ def longestDistance(graph):
|
||||
for x in graph[vertex]:
|
||||
indegree[x] -= 1
|
||||
|
||||
if longDist[vertex] + 1 > longDist[x]:
|
||||
longDist[x] = longDist[vertex] + 1
|
||||
if long_dist[vertex] + 1 > long_dist[x]:
|
||||
long_dist[x] = long_dist[vertex] + 1
|
||||
|
||||
if indegree[x] == 0:
|
||||
queue.append(x)
|
||||
|
||||
print(max(longDist))
|
||||
print(max(long_dist))
|
||||
|
||||
|
||||
# Adjacency list of Graph
|
||||
graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
|
||||
longestDistance(graph)
|
||||
longest_distance(graph)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
def topologicalSort(graph):
|
||||
def topological_sort(graph):
|
||||
"""
|
||||
Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph
|
||||
using BFS
|
||||
@@ -33,4 +33,4 @@ def topologicalSort(graph):
|
||||
|
||||
# Adjacency List of Graph
|
||||
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
|
||||
topologicalSort(graph)
|
||||
topological_sort(graph)
|
||||
|
||||
@@ -2,15 +2,15 @@ import sys
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def PrimsAlgorithm(l): # noqa: E741
|
||||
def prisms_algorithm(l): # noqa: E741
|
||||
|
||||
nodePosition = []
|
||||
node_position = []
|
||||
|
||||
def get_position(vertex):
|
||||
return nodePosition[vertex]
|
||||
return node_position[vertex]
|
||||
|
||||
def set_position(vertex, pos):
|
||||
nodePosition[vertex] = pos
|
||||
node_position[vertex] = pos
|
||||
|
||||
def top_to_bottom(heap, start, size, positions):
|
||||
if start > size // 2 - 1:
|
||||
@@ -64,44 +64,44 @@ def PrimsAlgorithm(l): # noqa: E741
|
||||
for i in range(start, -1, -1):
|
||||
top_to_bottom(heap, i, len(heap), positions)
|
||||
|
||||
def deleteMinimum(heap, positions):
|
||||
def delete_minimum(heap, positions):
|
||||
temp = positions[0]
|
||||
heap[0] = sys.maxsize
|
||||
top_to_bottom(heap, 0, len(heap), positions)
|
||||
return temp
|
||||
|
||||
visited = [0 for i in range(len(l))]
|
||||
Nbr_TV = [-1 for i in range(len(l))] # Neighboring Tree Vertex of selected vertex
|
||||
nbr_tv = [-1 for i in range(len(l))] # Neighboring Tree Vertex of selected vertex
|
||||
# Minimum Distance of explored vertex with neighboring vertex of partial tree
|
||||
# formed in graph
|
||||
Distance_TV = [] # Heap of Distance of vertices from their neighboring vertex
|
||||
Positions = []
|
||||
distance_tv = [] # Heap of Distance of vertices from their neighboring vertex
|
||||
positions = []
|
||||
|
||||
for x in range(len(l)):
|
||||
p = sys.maxsize
|
||||
Distance_TV.append(p)
|
||||
Positions.append(x)
|
||||
nodePosition.append(x)
|
||||
distance_tv.append(p)
|
||||
positions.append(x)
|
||||
node_position.append(x)
|
||||
|
||||
TreeEdges = []
|
||||
tree_edges = []
|
||||
visited[0] = 1
|
||||
Distance_TV[0] = sys.maxsize
|
||||
distance_tv[0] = sys.maxsize
|
||||
for x in l[0]:
|
||||
Nbr_TV[x[0]] = 0
|
||||
Distance_TV[x[0]] = x[1]
|
||||
heapify(Distance_TV, Positions)
|
||||
nbr_tv[x[0]] = 0
|
||||
distance_tv[x[0]] = x[1]
|
||||
heapify(distance_tv, positions)
|
||||
|
||||
for i in range(1, len(l)):
|
||||
vertex = deleteMinimum(Distance_TV, Positions)
|
||||
vertex = delete_minimum(distance_tv, positions)
|
||||
if visited[vertex] == 0:
|
||||
TreeEdges.append((Nbr_TV[vertex], vertex))
|
||||
tree_edges.append((nbr_tv[vertex], vertex))
|
||||
visited[vertex] = 1
|
||||
for v in l[vertex]:
|
||||
if visited[v[0]] == 0 and v[1] < Distance_TV[get_position(v[0])]:
|
||||
Distance_TV[get_position(v[0])] = v[1]
|
||||
bottom_to_top(v[1], get_position(v[0]), Distance_TV, Positions)
|
||||
Nbr_TV[v[0]] = vertex
|
||||
return TreeEdges
|
||||
if visited[v[0]] == 0 and v[1] < distance_tv[get_position(v[0])]:
|
||||
distance_tv[get_position(v[0])] = v[1]
|
||||
bottom_to_top(v[1], get_position(v[0]), distance_tv, positions)
|
||||
nbr_tv[v[0]] = vertex
|
||||
return tree_edges
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
@@ -113,4 +113,4 @@ if __name__ == "__main__": # pragma: no cover
|
||||
l = [int(x) for x in input().strip().split()] # noqa: E741
|
||||
adjlist[l[0]].append([l[1], l[2]])
|
||||
adjlist[l[1]].append([l[0], l[2]])
|
||||
print(PrimsAlgorithm(adjlist))
|
||||
print(prisms_algorithm(adjlist))
|
||||
|
||||
@@ -55,21 +55,21 @@ class PriorityQueue:
|
||||
return (priority, item)
|
||||
|
||||
|
||||
def consistent_heuristic(P: TPos, goal: TPos):
|
||||
def consistent_heuristic(p: TPos, goal: TPos):
|
||||
# euclidean distance
|
||||
a = np.array(P)
|
||||
a = np.array(p)
|
||||
b = np.array(goal)
|
||||
return np.linalg.norm(a - b)
|
||||
|
||||
|
||||
def heuristic_2(P: TPos, goal: TPos):
|
||||
def heuristic_2(p: TPos, goal: TPos):
|
||||
# integer division by time variable
|
||||
return consistent_heuristic(P, goal) // t
|
||||
return consistent_heuristic(p, goal) // t
|
||||
|
||||
|
||||
def heuristic_1(P: TPos, goal: TPos):
|
||||
def heuristic_1(p: TPos, goal: TPos):
|
||||
# manhattan distance
|
||||
return abs(P[0] - goal[0]) + abs(P[1] - goal[1])
|
||||
return abs(p[0] - goal[0]) + abs(p[1] - goal[1])
|
||||
|
||||
|
||||
def key(start: TPos, i: int, goal: TPos, g_function: dict[TPos, float]):
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
|
||||
def dfs(u):
|
||||
global graph, reversedGraph, scc, component, visit, stack
|
||||
global graph, reversed_graph, scc, component, visit, stack
|
||||
if visit[u]:
|
||||
return
|
||||
visit[u] = True
|
||||
@@ -12,17 +12,17 @@ def dfs(u):
|
||||
|
||||
|
||||
def dfs2(u):
|
||||
global graph, reversedGraph, scc, component, visit, stack
|
||||
global graph, reversed_graph, scc, component, visit, stack
|
||||
if visit[u]:
|
||||
return
|
||||
visit[u] = True
|
||||
component.append(u)
|
||||
for v in reversedGraph[u]:
|
||||
for v in reversed_graph[u]:
|
||||
dfs2(v)
|
||||
|
||||
|
||||
def kosaraju():
|
||||
global graph, reversedGraph, scc, component, visit, stack
|
||||
global graph, reversed_graph, scc, component, visit, stack
|
||||
for i in range(n):
|
||||
dfs(i)
|
||||
visit = [False] * n
|
||||
@@ -40,12 +40,12 @@ if __name__ == "__main__":
|
||||
n, m = list(map(int, input().strip().split()))
|
||||
|
||||
graph: list[list[int]] = [[] for i in range(n)] # graph
|
||||
reversedGraph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
||||
reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
||||
# input graph data (edges)
|
||||
for i in range(m):
|
||||
u, v = list(map(int, input().strip().split()))
|
||||
graph[u].append(v)
|
||||
reversedGraph[v].append(u)
|
||||
reversed_graph[v].append(u)
|
||||
|
||||
stack: list[int] = []
|
||||
visit: list[bool] = [False] * n
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from collections import defaultdict
|
||||
|
||||
from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst
|
||||
from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst
|
||||
|
||||
|
||||
def test_prim_successful_result():
|
||||
|
||||
Reference in New Issue
Block a user