My code does run but does not run as it should. Mu code should run with Dijkstra's Algorithm. Could you fix my code belo
Posted: Thu May 05, 2022 12:44 pm
My code does run but does not run as it should.
Mu code should run with Dijkstra's Algorithm. Could you fix my
code below?
#-----------------------------------------------
# CSC 211 Dijkstra's Algorithm Implementation
#-----------------------------------------------
class LinkedQueue(AbstractCollection):
"""A link-based queue implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self,
which includes the
contents of sourceCollection, if it's
present."""
self.front = self.rear = None
AbstractCollection.__init__(self,
sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of
self."""
cursor = self.front
while not cursor is None:
yield cursor.data
cursor =
cursor.next
def peek(self):
"""
Returns the item at the front of the
queue.
Precondition: the queue is not
empty.
Raises: KeyError if the stack is
empty."""
if self.isEmpty():
raise KeyError("The queue
is empty.")
return self.front.data
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.size = 0
self.front = self.rear = None
def add(self, item):
"""Adds item to the rear of the
queue."""
newNode = Node(item, None)
if self.isEmpty():
self.front =
newNode
else:
self.rear.next =
newNode
self.rear = newNode
self.size += 1
def pop(self):
"""
Removes and returns the item at the
front of the queue.
Precondition: the queue is not
empty.
Raises: KeyError if the queue is
empty.
Postcondition: the front item is
removed from the queue."""
if self.isEmpty():
raise KeyError("The queue
is empty.")
oldItem = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
self.size -= 1
return oldItem
--------------------------------
class LinkedStack(AbstractStack):
"""A link-based stack implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self,
which includes the
contents of sourceCollection, if it's
present."""
self.items = None
AbstractStack.__init__(self,
sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of
self.
Visits items from bottom to top of
stack."""
def visitNodes(node):
"""Adds items to tempList
from tail to head."""
if not node is
None:
visitNodes(node.next)
tempList.append(node.data)
tempList = list()
visitNodes(self.items)
return iter(tempList)
def peek(self):
"""
Returns the item at the top of the
stack.
Precondition: the stack is not
empty.
Raises: KeyError if the stack is
empty."""
if self.isEmpty():
raise KeyError("The stack
is empty.")
return self.items.data
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.size = 0
self.items = None
def push(self, item):
"""Adds item to the top of the
stack."""
self.items = Node(item,
self.items)
self.size += 1
def pop(self):
"""
Removes and returns the item at the top
of the stack.
Precondition: the stack is not
empty.
Raises: KeyError if the stack is
empty.
Postcondition: the top item is removed
from the stack."""
if self.isEmpty():
raise KeyError("The stack
is empty.")
data = self.items.data
self.items = self.items.next
self.size -= 1
return data
----------------------------------------------------------------
from graph import LinkedDirectedGraph
from linkedqueue import LinkedQueue
from linkedstack import LinkedStack
def dijkstra(g, i):
'''
Dijkstra's Algorithm
for graph g, starting with vertex i
'''
# initialize values
n=g.sizeVertices() # number of vertices to add
D=[] # D is the cost/distance to add vertex i
V=[] # V is the vertex in the MST adjacent to i
for j in range(0,n):
D.append(float('inf'))
V.append(None)
# create MST and add vertex i into it
D=0
mst = LinkedDirectedGraph()
mst.addVertex(i)
g.getVertex(i).setMark()
# recently added vertex
minIndex=i
# add vertices until the mst has as many vertices as g
while mst.sizeVertices()
# update D and V based on minIndex
for w in g.neighboringVertices(minIndex):
if not w.isMarked():
k=w.getLabel()
edgeVal = g.getEdge(minIndex,k).getWeight()
if D[k]>edgeVal:
D[k]=edgeVal
V[k]=minIndex
# find the first unvisited vertex
k=-1
j=0
while k<0 and j if not g.getVertex(j).isMarked():
k=j
j+=1
# find minimum cost unvisited vertex
minIndex=k
for j in range(0,n):
if not g.getVertex(j).isMarked():
if D[j] minIndex=j
# add new vertex to the MST and mark it in g
edgeVal = g.getEdge(V[minIndex],minIndex).getWeight()
mst.addVertex(minIndex)
mst.addEdge(minIndex,V[minIndex],edgeVal)
mst.addEdge(V[minIndex],minIndex,edgeVal)
g.getVertex(minIndex).setMark()
print("D= ", D)
print("V= ", V)
return mst
print('\n\n this method needs work!')
#-----------------------------------
# Test out the method below
g = LinkedDirectedGraph()
# add vertices
for i in range(0,9):
g.addVertex(i)
# add edges
g.addEdge(0,1,3.8)
g.addEdge(1,0,3.8)
g.addEdge(1,2,1.3)
g.addEdge(2,1,1.3)
g.addEdge(3,4,1.6)
g.addEdge(4,3,1.6)
g.addEdge(4,5,3.1)
g.addEdge(5,4,3.1)
g.addEdge(6,7,4.3)
g.addEdge(7,7,4.3)
g.addEdge(7,8,1.1)
g.addEdge(8,7,1.1)
g.addEdge(0,3,0.6)
g.addEdge(3,0,0.6)
g.addEdge(1,4,1.2)
g.addEdge(4,1,1.2)
g.addEdge(2,5,0.7)
g.addEdge(5,2,0.7)
g.addEdge(3,6,2.2)
g.addEdge(6,3,2.2)
g.addEdge(4,7,3.4)
g.addEdge(7,4,3.4)
g.addEdge(5,8,1.2)
g.addEdge(8,5,1.2)
print(g)
# try it out
dijkstra(g,0)
-------------------------------------------------
output
9 Vertices: 0 1 2 3 4 5 6 7 8
24 Edges: 0>1:3.8 0>3:0.6 1>0:3.8 1>2:1.3 1>4:1.2
2>1:1.3 2>5:0.7 3>4:1.6 3>0:0.6 3>6:2.2 4>3:1.6
4>5:3.1 4>1:1.2 4>7:3.4 5>4:3.1 5>2:0.7 5>8:1.2
6>7:4.3 6>3:2.2 7>7:4.3 7>8:1.1 7>4:3.4 8>7:1.1
8>5:1.2
D= [0, 1.2, 1.3, 0.6, 1.6, 0.7, 2.2, 1.1, 1.2]
V= [None, 4, 1, 0, 3, 2, 3, 8, 5]
I would be happy if you mention where you fix it.
Thank you
Mu code should run with Dijkstra's Algorithm. Could you fix my
code below?
#-----------------------------------------------
# CSC 211 Dijkstra's Algorithm Implementation
#-----------------------------------------------
class LinkedQueue(AbstractCollection):
"""A link-based queue implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self,
which includes the
contents of sourceCollection, if it's
present."""
self.front = self.rear = None
AbstractCollection.__init__(self,
sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of
self."""
cursor = self.front
while not cursor is None:
yield cursor.data
cursor =
cursor.next
def peek(self):
"""
Returns the item at the front of the
queue.
Precondition: the queue is not
empty.
Raises: KeyError if the stack is
empty."""
if self.isEmpty():
raise KeyError("The queue
is empty.")
return self.front.data
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.size = 0
self.front = self.rear = None
def add(self, item):
"""Adds item to the rear of the
queue."""
newNode = Node(item, None)
if self.isEmpty():
self.front =
newNode
else:
self.rear.next =
newNode
self.rear = newNode
self.size += 1
def pop(self):
"""
Removes and returns the item at the
front of the queue.
Precondition: the queue is not
empty.
Raises: KeyError if the queue is
empty.
Postcondition: the front item is
removed from the queue."""
if self.isEmpty():
raise KeyError("The queue
is empty.")
oldItem = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
self.size -= 1
return oldItem
--------------------------------
class LinkedStack(AbstractStack):
"""A link-based stack implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self,
which includes the
contents of sourceCollection, if it's
present."""
self.items = None
AbstractStack.__init__(self,
sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of
self.
Visits items from bottom to top of
stack."""
def visitNodes(node):
"""Adds items to tempList
from tail to head."""
if not node is
None:
visitNodes(node.next)
tempList.append(node.data)
tempList = list()
visitNodes(self.items)
return iter(tempList)
def peek(self):
"""
Returns the item at the top of the
stack.
Precondition: the stack is not
empty.
Raises: KeyError if the stack is
empty."""
if self.isEmpty():
raise KeyError("The stack
is empty.")
return self.items.data
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.size = 0
self.items = None
def push(self, item):
"""Adds item to the top of the
stack."""
self.items = Node(item,
self.items)
self.size += 1
def pop(self):
"""
Removes and returns the item at the top
of the stack.
Precondition: the stack is not
empty.
Raises: KeyError if the stack is
empty.
Postcondition: the top item is removed
from the stack."""
if self.isEmpty():
raise KeyError("The stack
is empty.")
data = self.items.data
self.items = self.items.next
self.size -= 1
return data
----------------------------------------------------------------
from graph import LinkedDirectedGraph
from linkedqueue import LinkedQueue
from linkedstack import LinkedStack
def dijkstra(g, i):
'''
Dijkstra's Algorithm
for graph g, starting with vertex i
'''
# initialize values
n=g.sizeVertices() # number of vertices to add
D=[] # D is the cost/distance to add vertex i
V=[] # V is the vertex in the MST adjacent to i
for j in range(0,n):
D.append(float('inf'))
V.append(None)
# create MST and add vertex i into it
D=0
mst = LinkedDirectedGraph()
mst.addVertex(i)
g.getVertex(i).setMark()
# recently added vertex
minIndex=i
# add vertices until the mst has as many vertices as g
while mst.sizeVertices()
# update D and V based on minIndex
for w in g.neighboringVertices(minIndex):
if not w.isMarked():
k=w.getLabel()
edgeVal = g.getEdge(minIndex,k).getWeight()
if D[k]>edgeVal:
D[k]=edgeVal
V[k]=minIndex
# find the first unvisited vertex
k=-1
j=0
while k<0 and j if not g.getVertex(j).isMarked():
k=j
j+=1
# find minimum cost unvisited vertex
minIndex=k
for j in range(0,n):
if not g.getVertex(j).isMarked():
if D[j] minIndex=j
# add new vertex to the MST and mark it in g
edgeVal = g.getEdge(V[minIndex],minIndex).getWeight()
mst.addVertex(minIndex)
mst.addEdge(minIndex,V[minIndex],edgeVal)
mst.addEdge(V[minIndex],minIndex,edgeVal)
g.getVertex(minIndex).setMark()
print("D= ", D)
print("V= ", V)
return mst
print('\n\n this method needs work!')
#-----------------------------------
# Test out the method below
g = LinkedDirectedGraph()
# add vertices
for i in range(0,9):
g.addVertex(i)
# add edges
g.addEdge(0,1,3.8)
g.addEdge(1,0,3.8)
g.addEdge(1,2,1.3)
g.addEdge(2,1,1.3)
g.addEdge(3,4,1.6)
g.addEdge(4,3,1.6)
g.addEdge(4,5,3.1)
g.addEdge(5,4,3.1)
g.addEdge(6,7,4.3)
g.addEdge(7,7,4.3)
g.addEdge(7,8,1.1)
g.addEdge(8,7,1.1)
g.addEdge(0,3,0.6)
g.addEdge(3,0,0.6)
g.addEdge(1,4,1.2)
g.addEdge(4,1,1.2)
g.addEdge(2,5,0.7)
g.addEdge(5,2,0.7)
g.addEdge(3,6,2.2)
g.addEdge(6,3,2.2)
g.addEdge(4,7,3.4)
g.addEdge(7,4,3.4)
g.addEdge(5,8,1.2)
g.addEdge(8,5,1.2)
print(g)
# try it out
dijkstra(g,0)
-------------------------------------------------
output
9 Vertices: 0 1 2 3 4 5 6 7 8
24 Edges: 0>1:3.8 0>3:0.6 1>0:3.8 1>2:1.3 1>4:1.2
2>1:1.3 2>5:0.7 3>4:1.6 3>0:0.6 3>6:2.2 4>3:1.6
4>5:3.1 4>1:1.2 4>7:3.4 5>4:3.1 5>2:0.7 5>8:1.2
6>7:4.3 6>3:2.2 7>7:4.3 7>8:1.1 7>4:3.4 8>7:1.1
8>5:1.2
D= [0, 1.2, 1.3, 0.6, 1.6, 0.7, 2.2, 1.1, 1.2]
V= [None, 4, 1, 0, 3, 2, 3, 8, 5]
I would be happy if you mention where you fix it.
Thank you