This might seem like an odd question, but I have a project for school, to make a weighted unordered graph but without using classes or numpy. Can anyone give me some advice on how to start?
from collections import defaultdict
#This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self,vertices):
self.V = vertices #No. of vertices
self.V_org = vertices
self.graph = defaultdict(list) # default dictionary to store graph
# function to add an edge to graph
def addEdge(self,u,v,w):
if w == 1:
self.graph[u].append(v)
else:
self.graph[u].append(self.V)
self.graph[self.V].append(v)
self.V = self.V + 1
# To print the shortest path stored in parent[]
def printPath(self, parent, j):
Path_len = 1
if parent[j] == -1 and j < self.V_org : #Base Case : If j is source
print (j)
return 0 # when parent[-1] then path length = 0
l = self.printPath(parent , parent[j])
Path_len = l + Path_len
if j < self.V_org :
print (j)
return Path_len
def findShortestPath(self,src, dest):
visited =[False]*(self.V)
parent =[-1]*(self.V)
# Create a queue for BFS
queue=[]
# Mark the source node as visited and enqueue it
queue.append(src)
visited[src] = True
while queue :
# Dequeue a vertex from queue
s = queue.pop(0)
# if s = dest then print the path and return
if s == dest:
return self.printPath(parent, s)
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
parent[i] = s
This is what I made using classes. If the question is not related to this forum I will delete it. Also I am not that experimented with python, I mostly write in C++ so I am not sure if python has struct or I was thinking of using a vector of pairs to store first vertex, second vertex and the weight.