Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions DSAGraphTestHarness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
from Graphy import *
import numpy as np
import io
from contextlib import redirect_stdout

# reference
# code to capture print out put from function
# Author: ForeverWintr (Dec 5, 2016)
# Stackoverflow How to capture stdout output from a Python function call?(May 15, 2013)
# Used in tests 4-7

numTest = 0
numPass = 0


print("\nTest 1 - Graph Creation ")
print("======================")
try:
numTest +=1
myGraph = DSAGraph()
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 2 - Add Vertexs")
print("======================")
try:
numTest +=1
myGraph.inputHandler('A','B',10.2) # create node a and b and connecs them
myGraph.inputHandler('A','C',15.4)
myGraph.inputHandler('B','C',3.2)
myGraph.inputHandler('D','C',1.0)
myGraph.inputHandler('B','E',5.8)
myGraph.inputHandler('A','E',4.9)
myGraph.inputHandler('F','E',7.2)
if myGraph.hasVertex('A') is not True:
raise Exception("Vertex not added")
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 3 - Edges ")
print("======================")
try:
numTest +=1
if myGraph.isAdjacent('B','C') is not True:
raise Exception("Edge not present")
numPass +=1
print("Passed")
except:
print("Failed")


print("\nTest 4 - Adjaceny List ")
print("======================")
try:
numTest +=1
f = io.StringIO()
with redirect_stdout(f):
myGraph.displayAsList()
out = f.getvalue()
lines =out.split("\n")
if lines[0].strip() != "A : ['B' 'C' 'E']":
raise Exception("Adjaceny list failed")
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 5 - Adjaceny Matrix")
print("======================")
try:
numTest +=1
f = io.StringIO()
with redirect_stdout(f):
myGraph.displayAsMatrix()
out = f.getvalue()
lines =out.split("\n")

if lines[0].strip() != '0 1 1 0 1 0':
raise Exception("Adjaceny Matrix not correct")
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 6 - BredthFirstSearch")
print("======================")
try:
numTest +=1
f = io.StringIO()
with redirect_stdout(f):
myGraph.breadFirstSearch()
out = f.getvalue()
lines = " ".join(out.splitlines())
lines = lines.split(':')
print(lines)
if lines[2].strip() != 'A B C E D F':
raise Exception("BreadthFirstSearch Failed")
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 7 - DepthFirstSearch")
print("======================")
try:
numTest +=1

f = io.StringIO()
with redirect_stdout(f):
myGraph.deepFirstSearch()
out = f.getvalue()
lines = " ".join(out.splitlines())
lines = lines.split(':')
print(lines)
if lines[1].strip() != 'A B C D E F':
raise Exception("DepthFirstSearch Failed")
numPass +=1
print("Passed")
except:
print("Failed")

print("\nTest 8 - Edge Weight ")
print("======================")
#try:
numTest +=1
vertex1 = myGraph.getVertex('A')
edges = vertex1.getAdjacent()
print(edges)
if 1+2 ==4:
pass
numPass +=1
print("Passed")
#except:
print("Failed")

print("\n Test results")
print(str(numPass)+"/"+str(numTest))
print(str(numPass/numTest*100)+"% passed")
126 changes: 126 additions & 0 deletions DSAHeap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
from DSAHeapEntry import *
import numpy as np

class DSAHeap():

def __init__(self,size) -> None:
self.heap = np.zeros(size,dtype=object)
for i in range(len(self.heap)):
self.heap[i] = DSAHeapEntry()
self.count = 0
self.length = size

def add(self,priority,value):
try:
if self.count == self.length:
raise IndexError("Heap is full")
if type(priority) == str:
if not priority.isdigit():
raise AttributeError("Non integer value")
priority = int(priority)
if priority <= 0:
raise ValueError("Negative Value detected for priority")
if not value:
raise ValueError("Empty Value string detected")
except AttributeError as e:
print("Invalid priority: "+str(e))
except ValueError as e:
print("Invalid input: "+str(e))
except IndexError as e:
print("Exceeded heap boundaries: "+str(e))
else:
self._add(priority,value)

def _add(self,priority,value):
self.heap[self.count].setPriority(priority)
self.heap[self.count].setValue(value)
self.trickleUp(self.count,self.heap)
self.count +=1

def remove(self):
try:
if self.count == 0 or self.heap[0].getPriority() == None:
raise IndexError("Cannot remove from empty list")
root = self.heap[0]
self.heap[0]=self.heap[self.count-1]
self.count -=1
self.trickleDown(0)
except IndexError as e:
print("List empty: "+str(e))
else:
return root
'''
temp = self.heap[0]
if self.count == 1:
self.heap = np.zeros(self.length,dtype=object)
for i in range(len(self.heap)):
self.heap[i] = DSAHeapEntry()
else:
self.heap[0]=self.heap[self.count-1]
self.trickleDown(0,self.heap)
self.count -= 1
except IndexError as e:
print("List empty: "+str(e))
else:
return temp '''


def display(self):
for item in self.heap:
if item.getPriority() is not None:
print("Priority: "+str(item.getPriority()))
print("Value: "+str(item.getValue()))
print()

def trickleUp(self,index,heapArr):
parentIdn = int((index -1)/2)
if index > 0 and heapArr[index].getPriority() is not None and heapArr[parentIdn].getPriority() is not None:
if self.heap[index].getPriority() > self.heap[parentIdn].getPriority():
temp = heapArr[parentIdn]
heapArr[parentIdn] = heapArr[index]
heapArr[index] = temp
self.trickleUp(parentIdn,heapArr)

def trickleDown(self,index):
lChild = 2*index+1
rChild = 2*index+2
largest = index

if lChild < self.count and self.heap[lChild].getPriority() > self.heap[largest].getPriority():
largest = lChild
if rChild < self.count and self.heap[rChild].getPriority() > self.heap[largest].getPriority():
largest = rChild
if largest != index:
temp =self.heap[index]
self.heap[index] = self.heap[largest]
self.heap[largest]=temp
self.trickleDown(largest)

def trickleDown2(self,index,heapArr):
lChild = index * 2 +1
rChild = lChild + 1
if lChild < len(heapArr):
largeInd = lChild
if rChild < len(heapArr):
if heapArr[lChild].getPriority() < heapArr[rChild].getPriority():
largeInd = rChild
if heapArr[largeInd].getPriority() > heapArr[index].getPriority():
temp = heapArr[largeInd]
heapArr[largeInd] = heapArr[index]
heapArr[index] = temp
self.trickleDown(largeInd)

def heapify(self,heapArr):
for i in range(int(len(heapArr)/2)-1,-1,-1):
self.trickleDown(i)
return heapArr

def heapSort(self,heapArr):
heapArr = self.heapify(heapArr)
i = len(heapArr)-1
for i in range(len(heapArr)-1,0,-1):
temp = heapArr[0]
heapArr[0] = heapArr[i]
heapArr[i] = temp
self.trickleDown(0)
self.heap = heapArr
17 changes: 17 additions & 0 deletions DSAHeapEntry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

class DSAHeapEntry():
def __init__(self,priority = None, value= None):
self.priority = priority
self.value = value

def getPriority(self):
return self.priority

def setPriority(self, priority):
self.priority = priority

def getValue(self) -> object:
return self.value

def setValue(self,value):
self.value = value
Loading