Tighten up psf/black and flake8 (#2024)

* Tighten up psf/black and flake8

* Fix some tests

* Fix some E741

* Fix some E741

* updating DIRECTORY.md

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Christian Clauss
2020-05-22 08:10:11 +02:00
committed by GitHub
parent 21ed8968c0
commit 1f8a21d727
124 changed files with 583 additions and 495 deletions

View File

@@ -1,5 +1,5 @@
# Finding Articulation Points in Undirected Graph
def computeAP(l):
def computeAP(l): # noqa: E741
n = len(l)
outEdgeCount = 0
low = [0] * n
@@ -36,12 +36,12 @@ def computeAP(l):
isArt[i] = outEdgeCount > 1
for x in range(len(isArt)):
if isArt[x] == True:
if isArt[x] is True:
print(x)
# Adjacency list of graph
l = {
data = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
@@ -52,4 +52,4 @@ l = {
7: [6, 8],
8: [5, 7],
}
computeAP(l)
computeAP(data)

View File

@@ -1,3 +1,6 @@
from collections import deque
if __name__ == "__main__":
# Accept No. of Nodes and edges
n, m = map(int, input().split(" "))
@@ -72,7 +75,6 @@ def dfs(G, s):
Q - Traversal Stack
--------------------------------------------------------------------------------
"""
from collections import deque
def bfs(G, s):
@@ -125,7 +127,6 @@ def dijk(G, s):
Topological Sort
--------------------------------------------------------------------------------
"""
from collections import deque
def topo(G, ind=None, Q=None):
@@ -235,10 +236,10 @@ def prim(G, s):
def edglist():
n, m = map(int, input().split(" "))
l = []
edges = []
for i in range(m):
l.append(map(int, input().split(" ")))
return l, n
edges.append(map(int, input().split(" ")))
return edges, n
"""

View File

@@ -9,7 +9,7 @@ def printDist(dist, V):
def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int:
"""
Returns shortest paths from a vertex src to all
Returns shortest paths from a vertex src to all
other vertices.
"""
mdist = [float("inf") for i in range(V)]

View File

@@ -1,6 +1,8 @@
"""Breath First Search (BFS) can be used when finding the shortest path
"""Breath First Search (BFS) can be used when finding the shortest path
from a given source node to a target node in an unweighted graph.
"""
from typing import Dict
graph = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
@@ -11,8 +13,6 @@ graph = {
"G": ["C"],
}
from typing import Dict
class Graph:
def __init__(self, graph: Dict[str, str], source_vertex: str) -> None:
@@ -46,8 +46,9 @@ class Graph:
def shortest_path(self, target_vertex: str) -> str:
"""This shortest path function returns a string, describing the result:
1.) No path is found. The string is a human readable message to indicate this.
2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`,
where v1 is the source vertex and vn is the target vertex, if it exists separately.
2.) The shortest path is found. The string is in the form
`v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target
vertex, if it exists separately.
>>> g = Graph(graph, "G")
>>> g.breath_first_search()

View File

@@ -1,21 +1,22 @@
# Check whether Graph is Bipartite or Not using BFS
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.
def checkBipartite(l):
def checkBipartite(graph):
queue = []
visited = [False] * len(l)
color = [-1] * len(l)
visited = [False] * len(graph)
color = [-1] * len(graph)
def bfs():
while queue:
u = queue.pop(0)
visited[u] = True
for neighbour in l[u]:
for neighbour in graph[u]:
if neighbour == u:
return False
@@ -29,16 +30,16 @@ def checkBipartite(l):
return True
for i in range(len(l)):
for i in range(len(graph)):
if not visited[i]:
queue.append(i)
color[i] = 0
if bfs() == False:
if bfs() is False:
return False
return True
# Adjacency List of graph
l = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}
print(checkBipartite(l))
if __name__ == "__main__":
# Adjacency List of graph
print(checkBipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}))

View File

@@ -1,27 +1,28 @@
# Check whether Graph is Bipartite or Not using DFS
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.
def check_bipartite_dfs(l):
visited = [False] * len(l)
color = [-1] * len(l)
def check_bipartite_dfs(graph):
visited = [False] * len(graph)
color = [-1] * len(graph)
def dfs(v, c):
visited[v] = True
color[v] = c
for u in l[v]:
for u in graph[v]:
if not visited[u]:
dfs(u, 1 - c)
for i in range(len(l)):
for i in range(len(graph)):
if not visited[i]:
dfs(i, 0)
for i in range(len(l)):
for j in l[i]:
for i in range(len(graph)):
for j in graph[i]:
if color[i] == color[j]:
return False
@@ -29,5 +30,5 @@ def check_bipartite_dfs(l):
# Adjacency list of graph
l = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []}
print(check_bipartite_dfs(l))
graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []}
print(check_bipartite_dfs(graph))

View File

@@ -1,6 +1,6 @@
"""The DFS function simply calls itself recursively for every unvisited child of
its argument. We can emulate that behaviour precisely using a stack of iterators.
Instead of recursively calling with a node, we'll push an iterator to the node's
"""The DFS function simply calls itself recursively for every unvisited child of
its argument. We can emulate that behaviour precisely using a stack of iterators.
Instead of recursively calling with a node, we'll push an iterator to the node's
children onto the iterator stack. When the iterator at the top of the stack
terminates, we'll pop it off the stack.
@@ -21,7 +21,7 @@ def depth_first_search(graph: Dict, start: str) -> Set[int]:
:param graph: directed graph in dictionary format
:param vertex: starting vectex as a string
:returns: the trace of the search
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
>>> G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
... "F": ["C", "E", "G"], "G": ["F"] }
>>> start = "A"

View File

@@ -28,7 +28,7 @@ class Graph:
# call the recursive helper function
for i in range(len(self.vertex)):
if visited[i] == False:
if visited[i] is False:
self.DFSRec(i, visited)
def DFSRec(self, startVertex, visited):
@@ -39,7 +39,7 @@ class Graph:
# Recur for all the vertices that are adjacent to this node
for i in self.vertex.keys():
if visited[i] == False:
if visited[i] is False:
self.DFSRec(i, visited)

View File

@@ -1,6 +1,6 @@
"""pseudo-code"""
"""
pseudo-code
DIJKSTRA(graph G, start vertex s, destination vertex d):
//all nodes initially unexplored
@@ -30,7 +30,6 @@ only the distance between previous vertex and current vertex but the entire
distance between each vertex that makes up the path from start vertex to target
vertex.
"""
import heapq

View File

@@ -37,7 +37,7 @@ class Dinic:
# Here we calculate the flow that reaches the sink
def max_flow(self, source, sink):
flow, self.q[0] = 0, source
for l in range(31): # l = 30 maybe faster for random data
for l in range(31): # noqa: E741 l = 30 maybe faster for random data
while True:
self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q)
qi, qe, self.lvl[source] = 0, 1, 1

View File

@@ -71,8 +71,8 @@ class DirectedGraph:
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function the count
# will be random from 10 to 10000
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = (math.floor(rand.random() * 10000)) + 10
@@ -168,14 +168,14 @@ class DirectedGraph:
and indirect_parents.count(__[1]) > 0
and not on_the_way_back
):
l = len(stack) - 1
while True and l >= 0:
if stack[l] == __[1]:
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == __[1]:
anticipating_nodes.add(__[1])
break
else:
anticipating_nodes.add(stack[l])
l -= 1
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(__[1]) < 1:
stack.append(__[1])
visited.append(__[1])
@@ -221,15 +221,15 @@ class DirectedGraph:
and indirect_parents.count(__[1]) > 0
and not on_the_way_back
):
l = len(stack) - 1
while True and l >= 0:
if stack[l] == __[1]:
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == __[1]:
anticipating_nodes.add(__[1])
break
else:
return True
anticipating_nodes.add(stack[l])
l -= 1
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(__[1]) < 1:
stack.append(__[1])
visited.append(__[1])
@@ -341,8 +341,8 @@ class Graph:
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function the count
# will be random from 10 to 10000
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = (math.floor(rand.random() * 10000)) + 10
@@ -397,14 +397,14 @@ class Graph:
and indirect_parents.count(__[1]) > 0
and not on_the_way_back
):
l = len(stack) - 1
while True and l >= 0:
if stack[l] == __[1]:
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == __[1]:
anticipating_nodes.add(__[1])
break
else:
anticipating_nodes.add(stack[l])
l -= 1
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(__[1]) < 1:
stack.append(__[1])
visited.append(__[1])
@@ -450,15 +450,15 @@ class Graph:
and indirect_parents.count(__[1]) > 0
and not on_the_way_back
):
l = len(stack) - 1
while True and l >= 0:
if stack[l] == __[1]:
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == __[1]:
anticipating_nodes.add(__[1])
break
else:
return True
anticipating_nodes.add(stack[l])
l -= 1
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(__[1]) < 1:
stack.append(__[1])
visited.append(__[1])

View File

@@ -9,7 +9,7 @@
def dfs(u, graph, visited_edge, path=[]):
path = path + [u]
for v in graph[u]:
if visited_edge[u][v] == False:
if visited_edge[u][v] is False:
visited_edge[u][v], visited_edge[v][u] = True, True
path = dfs(v, graph, visited_edge, path)
return path

View File

@@ -1,7 +1,7 @@
# Finding Bridges in Undirected Graph
def computeBridges(l):
def computeBridges(graph):
id = 0
n = len(l) # No of vertices in graph
n = len(graph) # No of vertices in graph
low = [0] * n
visited = [False] * n
@@ -9,7 +9,7 @@ def computeBridges(l):
visited[at] = True
low[at] = id
id += 1
for to in l[at]:
for to in graph[at]:
if to == parent:
pass
elif not visited[to]:
@@ -28,7 +28,7 @@ def computeBridges(l):
print(bridges)
l = {
graph = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
@@ -39,4 +39,4 @@ l = {
7: [6, 8],
8: [5, 7],
}
computeBridges(l)
computeBridges(graph)

View File

@@ -19,7 +19,7 @@ edge_array = [
['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'bh-e12', 'cd-e2', 'df-e8', 'dh-e10'],
['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8',
'dg-e5', 'ef-e3', 'eg-e2', 'fg-e6']
]
]
# fmt: on

View File

@@ -1,10 +1,10 @@
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
def longestDistance(l):
indegree = [0] * len(l)
def longestDistance(graph):
indegree = [0] * len(graph)
queue = []
longDist = [1] * len(l)
longDist = [1] * len(graph)
for key, values in l.items():
for key, values in graph.items():
for i in values:
indegree[i] += 1
@@ -14,7 +14,7 @@ def longestDistance(l):
while queue:
vertex = queue.pop(0)
for x in l[vertex]:
for x in graph[vertex]:
indegree[x] -= 1
if longDist[vertex] + 1 > longDist[x]:
@@ -27,5 +27,5 @@ def longestDistance(l):
# Adjacency list of Graph
l = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longestDistance(l)
graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longestDistance(graph)

View File

@@ -1,11 +1,14 @@
# Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS
def topologicalSort(l):
indegree = [0] * len(l)
def topologicalSort(graph):
"""
Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph
using BFS
"""
indegree = [0] * len(graph)
queue = []
topo = []
cnt = 0
for key, values in l.items():
for key, values in graph.items():
for i in values:
indegree[i] += 1
@@ -17,17 +20,17 @@ def topologicalSort(l):
vertex = queue.pop(0)
cnt += 1
topo.append(vertex)
for x in l[vertex]:
for x in graph[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(x)
if cnt != len(l):
if cnt != len(graph):
print("Cycle exists")
else:
print(topo)
# Adjacency List of Graph
l = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topologicalSort(l)
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
topologicalSort(graph)

View File

@@ -2,7 +2,7 @@ import sys
from collections import defaultdict
def PrimsAlgorithm(l):
def PrimsAlgorithm(l): # noqa: E741
nodePosition = []
@@ -109,7 +109,7 @@ if __name__ == "__main__":
e = int(input("Enter number of edges: ").strip())
adjlist = defaultdict(list)
for x in range(e):
l = [int(x) for x in input().strip().split()]
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))