Travis CI: Add pytest --doctest-modules graphs (#1018)

This commit is contained in:
cclauss 2019-07-17 06:07:25 +02:00 committed by GitHub
parent 267b5eff40
commit 7cdda931fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 145 additions and 132 deletions

View File

@ -21,6 +21,7 @@ script:
digital_image_processing digital_image_processing
divide_and_conquer divide_and_conquer
dynamic_programming dynamic_programming
graphs
hashes hashes
linear_algebra_python linear_algebra_python
matrix matrix

View File

@ -10,42 +10,44 @@ try:
except NameError: except NameError:
xrange = range # Python 3 xrange = range # Python 3
# Accept No. of Nodes and edges
n, m = map(int, raw_input().split(" "))
# Initialising Dictionary of edges if __name__ == "__main__":
g = {} # Accept No. of Nodes and edges
for i in xrange(n): n, m = map(int, raw_input().split(" "))
g[i + 1] = []
""" # Initialising Dictionary of edges
-------------------------------------------------------------------------------- g = {}
Accepting edges of Unweighted Directed Graphs for i in xrange(n):
-------------------------------------------------------------------------------- g[i + 1] = []
"""
for _ in xrange(m):
x, y = map(int, raw_input().split(" "))
g[x].append(y)
""" """
-------------------------------------------------------------------------------- ----------------------------------------------------------------------------
Accepting edges of Unweighted Undirected Graphs Accepting edges of Unweighted Directed Graphs
-------------------------------------------------------------------------------- ----------------------------------------------------------------------------
""" """
for _ in xrange(m): for _ in xrange(m):
x, y = map(int, raw_input().split(" ")) x, y = map(int, raw_input().strip().split(" "))
g[x].append(y) g[x].append(y)
g[y].append(x)
""" """
-------------------------------------------------------------------------------- ----------------------------------------------------------------------------
Accepting edges of Weighted Undirected Graphs Accepting edges of Unweighted Undirected Graphs
-------------------------------------------------------------------------------- ----------------------------------------------------------------------------
""" """
for _ in xrange(m): for _ in xrange(m):
x, y, r = map(int, raw_input().split(" ")) x, y = map(int, raw_input().strip().split(" "))
g[x].append([y, r]) g[x].append(y)
g[y].append([x, r]) g[y].append(x)
"""
----------------------------------------------------------------------------
Accepting edges of Weighted Undirected Graphs
----------------------------------------------------------------------------
"""
for _ in xrange(m):
x, y, r = map(int, raw_input().strip().split(" "))
g[x].append([y, r])
g[y].append([x, r])
""" """
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
@ -168,9 +170,10 @@ def topo(G, ind=None, Q=[1]):
def adjm(): def adjm():
n, a = raw_input(), [] n = raw_input().strip()
a = []
for i in xrange(n): for i in xrange(n):
a.append(map(int, raw_input().split())) a.append(map(int, raw_input().strip().split()))
return a, n return a, n

View File

@ -12,7 +12,7 @@ def printDist(dist, V):
def BellmanFord(graph, V, E, src): def BellmanFord(graph, V, E, src):
mdist=[float('inf') for i in range(V)] mdist=[float('inf') for i in range(V)]
mdist[src] = 0.0 mdist[src] = 0.0
for i in range(V-1): for i in range(V-1):
for j in range(V): for j in range(V):
u = graph[j]["src"] u = graph[j]["src"]
@ -20,7 +20,7 @@ def BellmanFord(graph, V, E, src):
w = graph[j]["weight"] w = graph[j]["weight"]
if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: if mdist[u] != float('inf') and mdist[u] + w < mdist[v]:
mdist[v] = mdist[u] + w mdist[v] = mdist[u] + w
for j in range(V): for j in range(V):
u = graph[j]["src"] u = graph[j]["src"]
v = graph[j]["dst"] v = graph[j]["dst"]
@ -29,26 +29,26 @@ def BellmanFord(graph, V, E, src):
if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: if mdist[u] != float('inf') and mdist[u] + w < mdist[v]:
print("Negative cycle found. Solution not possible.") print("Negative cycle found. Solution not possible.")
return return
printDist(mdist, V)
printDist(mdist, V)
#MAIN
V = int(input("Enter number of vertices: "))
E = int(input("Enter number of edges: "))
graph = [dict() for j in range(E)]
for i in range(V): if __name__ == "__main__":
graph[i][i] = 0.0 V = int(input("Enter number of vertices: ").strip())
E = int(input("Enter number of edges: ").strip())
for i in range(E): graph = [dict() for j in range(E)]
print("\nEdge ",i+1)
src = int(input("Enter source:")) for i in range(V):
dst = int(input("Enter destination:")) graph[i][i] = 0.0
weight = float(input("Enter weight:"))
graph[i] = {"src": src,"dst": dst, "weight": weight} for i in range(E):
print("\nEdge ",i+1)
gsrc = int(input("\nEnter shortest path source:")) src = int(input("Enter source:").strip())
BellmanFord(graph, V, E, gsrc) dst = int(input("Enter destination:").strip())
weight = float(input("Enter weight:").strip())
graph[i] = {"src": src,"dst": dst, "weight": weight}
gsrc = int(input("\nEnter shortest path source:").strip())
BellmanFord(graph, V, E, gsrc)

View File

@ -22,36 +22,36 @@ def Dijkstra(graph, V, src):
mdist=[float('inf') for i in range(V)] mdist=[float('inf') for i in range(V)]
vset = [False for i in range(V)] vset = [False for i in range(V)]
mdist[src] = 0.0 mdist[src] = 0.0
for i in range(V-1): for i in range(V-1):
u = minDist(mdist, vset, V) u = minDist(mdist, vset, V)
vset[u] = True vset[u] = True
for v in range(V): for v in range(V):
if (not vset[v]) and graph[u][v]!=float('inf') and mdist[u] + graph[u][v] < mdist[v]: if (not vset[v]) and graph[u][v]!=float('inf') and mdist[u] + graph[u][v] < mdist[v]:
mdist[v] = mdist[u] + graph[u][v] mdist[v] = mdist[u] + graph[u][v]
printDist(mdist, V)
printDist(mdist, V)
#MAIN
V = int(input("Enter number of vertices: "))
E = int(input("Enter number of edges: "))
graph = [[float('inf') for i in range(V)] for j in range(V)]
for i in range(V): if __name__ == "__main__":
graph[i][i] = 0.0 V = int(input("Enter number of vertices: ").strip())
E = int(input("Enter number of edges: ").strip())
for i in range(E): graph = [[float('inf') for i in range(V)] for j in range(V)]
print("\nEdge ",i+1)
src = int(input("Enter source:"))
dst = int(input("Enter destination:"))
weight = float(input("Enter weight:"))
graph[src][dst] = weight
gsrc = int(input("\nEnter shortest path source:")) for i in range(V):
Dijkstra(graph, V, gsrc) graph[i][i] = 0.0
for i in range(E):
print("\nEdge ",i+1)
src = int(input("Enter source:").strip())
dst = int(input("Enter destination:").strip())
weight = float(input("Enter weight:").strip())
graph[src][dst] = weight
gsrc = int(input("\nEnter shortest path source:").strip())
Dijkstra(graph, V, gsrc)

View File

@ -1,32 +1,34 @@
from __future__ import print_function from __future__ import print_function
num_nodes, num_edges = list(map(int,input().split()))
edges = [] if __name__ == "__main__":
num_nodes, num_edges = list(map(int, input().strip().split()))
for i in range(num_edges): edges = []
node1, node2, cost = list(map(int,input().split()))
edges.append((i,node1,node2,cost))
edges = sorted(edges, key=lambda edge: edge[3]) for i in range(num_edges):
node1, node2, cost = list(map(int, input().strip().split()))
edges.append((i,node1,node2,cost))
parent = [i for i in range(num_nodes)] edges = sorted(edges, key=lambda edge: edge[3])
def find_parent(i): parent = list(range(num_nodes))
if(i != parent[i]):
parent[i] = find_parent(parent[i])
return parent[i]
minimum_spanning_tree_cost = 0 def find_parent(i):
minimum_spanning_tree = [] if i != parent[i]:
parent[i] = find_parent(parent[i])
return parent[i]
for edge in edges: minimum_spanning_tree_cost = 0
parent_a = find_parent(edge[1]) minimum_spanning_tree = []
parent_b = find_parent(edge[2])
if(parent_a != parent_b):
minimum_spanning_tree_cost += edge[3]
minimum_spanning_tree.append(edge)
parent[parent_a] = parent_b
print(minimum_spanning_tree_cost) for edge in edges:
for edge in minimum_spanning_tree: parent_a = find_parent(edge[1])
print(edge) parent_b = find_parent(edge[2])
if parent_a != parent_b:
minimum_spanning_tree_cost += edge[3]
minimum_spanning_tree.append(edge)
parent[parent_a] = parent_b
print(minimum_spanning_tree_cost)
for edge in minimum_spanning_tree:
print(edge)

View File

@ -100,12 +100,13 @@ def PrimsAlgorithm(l):
Nbr_TV[ v[0] ] = vertex Nbr_TV[ v[0] ] = vertex
return TreeEdges return TreeEdges
# < --------- Prims Algorithm --------- > if __name__ == "__main__":
n = int(input("Enter number of vertices: ")) # < --------- Prims Algorithm --------- >
e = int(input("Enter number of edges: ")) n = int(input("Enter number of vertices: ").strip())
adjlist = defaultdict(list) e = int(input("Enter number of edges: ").strip())
for x in range(e): adjlist = defaultdict(list)
l = [int(x) for x in input().split()] for x in range(e):
adjlist[l[0]].append([ l[1], l[2] ]) l = [int(x) for x in input().strip().split()]
adjlist[l[1]].append([ l[0], l[2] ]) adjlist[l[0]].append([ l[1], l[2] ])
print(PrimsAlgorithm(adjlist)) adjlist[l[1]].append([ l[0], l[2] ])
print(PrimsAlgorithm(adjlist))

View File

@ -18,7 +18,7 @@ class PriorityQueue:
return self.elements[0][0] return self.elements[0][0]
else: else:
return float('inf') return float('inf')
def empty(self): def empty(self):
return len(self.elements) == 0 return len(self.elements) == 0
@ -48,10 +48,10 @@ class PriorityQueue:
(pro, x) = heapq.heappop(self.elements) (pro, x) = heapq.heappop(self.elements)
for (prito, yyy) in temp: for (prito, yyy) in temp:
heapq.heappush(self.elements, (prito, yyy)) heapq.heappush(self.elements, (prito, yyy))
def top_show(self): def top_show(self):
return self.elements[0][1] return self.elements[0][1]
def get(self): def get(self):
(priority, item) = heapq.heappop(self.elements) (priority, item) = heapq.heappop(self.elements)
self.set.remove(item) self.set.remove(item)
@ -65,7 +65,7 @@ def consistent_hueristic(P, goal):
def hueristic_2(P, goal): def hueristic_2(P, goal):
# integer division by time variable # integer division by time variable
return consistent_hueristic(P, goal) // t return consistent_hueristic(P, goal) // t
def hueristic_1(P, goal): def hueristic_1(P, goal):
# manhattan distance # manhattan distance
@ -74,13 +74,13 @@ def hueristic_1(P, goal):
def key(start, i, goal, g_function): def key(start, i, goal, g_function):
ans = g_function[start] + W1 * hueristics[i](start, goal) ans = g_function[start] + W1 * hueristics[i](start, goal)
return ans return ans
def do_something(back_pointer, goal, start): def do_something(back_pointer, goal, start):
grid = np.chararray((n, n)) grid = np.chararray((n, n))
for i in range(n): for i in range(n):
for j in range(n): for j in range(n):
grid[i][j] = '*' grid[i][j] = '*'
for i in range(n): for i in range(n):
for j in range(n): for j in range(n):
if (j, (n-1)-i) in blocks: if (j, (n-1)-i) in blocks:
@ -94,7 +94,7 @@ def do_something(back_pointer, goal, start):
grid[(n-1)-y_c][x_c] = "-" grid[(n-1)-y_c][x_c] = "-"
x = back_pointer[x] x = back_pointer[x]
grid[(n-1)][0] = "-" grid[(n-1)][0] = "-"
for i in xrange(n): for i in xrange(n):
for j in range(n): for j in range(n):
@ -112,7 +112,7 @@ def do_something(back_pointer, goal, start):
print("PATH TAKEN BY THE ALGORITHM IS:-") print("PATH TAKEN BY THE ALGORITHM IS:-")
x = back_pointer[goal] x = back_pointer[goal]
while x != start: while x != start:
print(x, end=' ') print(x, end=' ')
x = back_pointer[x] x = back_pointer[x]
print(x) print(x)
quit() quit()
@ -153,7 +153,7 @@ def expand_state(s, j, visited, g_function, close_list_anchor, close_list_inad,
if key(neighbours, var, goal, g_function) <= W2 * key(neighbours, 0, goal, g_function): if key(neighbours, var, goal, g_function) <= W2 * key(neighbours, 0, goal, g_function):
# print("why not plssssssssss") # print("why not plssssssssss")
open_list[j].put(neighbours, key(neighbours, var, goal, g_function)) open_list[j].put(neighbours, key(neighbours, var, goal, g_function))
# print # print
@ -212,7 +212,7 @@ def multi_a_star(start, goal, n_hueristic):
for i in range(n_hueristic): for i in range(n_hueristic):
open_list.append(PriorityQueue()) open_list.append(PriorityQueue())
open_list[i].put(start, key(start, i, goal, g_function)) open_list[i].put(start, key(start, i, goal, g_function))
close_list_anchor = [] close_list_anchor = []
close_list_inad = [] close_list_inad = []
while open_list[0].minkey() < float('inf'): while open_list[0].minkey() < float('inf'):
@ -263,4 +263,7 @@ def multi_a_star(start, goal, n_hueristic):
print() print()
print("# is an obstacle") print("# is an obstacle")
print("- is the path taken by algorithm") print("- is the path taken by algorithm")
multi_a_star(start, goal, n_hueristic)
if __name__ == "__main__":
multi_a_star(start, goal, n_hueristic)

View File

@ -1,19 +1,5 @@
from __future__ import print_function from __future__ import print_function
# n - no of nodes, m - no of edges
n, m = list(map(int,input().split()))
g = [[] for i in range(n)] #graph
r = [[] for i in range(n)] #reversed graph
# input graph data (edges)
for i in range(m):
u, v = list(map(int,input().split()))
g[u].append(v)
r[v].append(u)
stack = []
visit = [False]*n
scc = []
component = []
def dfs(u): def dfs(u):
global g, r, scc, component, visit, stack global g, r, scc, component, visit, stack
@ -43,4 +29,21 @@ def kosaraju():
scc.append(component) scc.append(component)
return scc return scc
print(kosaraju())
if __name__ == "__main__":
# n - no of nodes, m - no of edges
n, m = list(map(int,input().strip().split()))
g = [[] for i in range(n)] #graph
r = [[] for i in range(n)] #reversed graph
# input graph data (edges)
for i in range(m):
u, v = list(map(int,input().strip().split()))
g[u].append(v)
r[v].append(u)
stack = []
visit = [False]*n
scc = []
component = []
print(kosaraju())