def radix_sort_string(a, max): arr = DynamicArray(37) for i in range(len(arr.array)): arr.array[i] = DList() for i in range(max): print("================= Ordering by " + str(i + 1) + "place ======================") for item in a: if len(item) > (max - (max - i)): # print(item[i], end="") arr.array[ord(item[max - (max - len(item)) - (i + 1)].lower()) - 96].Append(x=item) else: # print("-", end="") arr.array[0].Append(x=item) h = 0 for k in arr.array: start = k.head if start is not None: while not k.IsEmpty(): print(start.data) temp = start.next a[h] = k.Remove(start.data) start = temp h += 1 return a
def read_bin_all(self): self._entities = DynamicArray() try: f = open(self._filename, 'rb') self._entities = pickle.load(f) except EOFError: self._entities = DynamicArray()
def read_bin_all(self): self._entities = DynamicArray() with open(self._filename) as f: json_string = json.dumps(json.load(f), default=self.obj_to_dict, indent=2) self._entities = json.loads(json_string, object_hook=self._classname.as_obj)
def read_all(self): self._entities = DynamicArray() with open(self._filename, "r") as f: lines = f.readlines() for line in lines: line = line.strip() if line != "": obj = self._read_object(line) self._entities.append(obj)
def read_data(self): #reads all the data from the sql table self._entities = DynamicArray() cmd = 'SELECT * FROM ' + self._table_name self._cursor.execute(cmd) line = self._cursor.fetchone() while line is not None: obj = Book(int(line[0]), line[1], line[2]) self._entities.append(obj) line = self._cursor.fetchone()
class Repo(object): def __init__(self, Name): self._name = Name self._entities = DynamicArray() def size(self): #returns the size of the repo return len(self._entities) def add(self, obj): #adds a new object (obj) to the repo #raises a RepositoryError if the id of the obj is invalid if obj in self._entities: raise RepositoryError(self._name + " Existing ID!\n") self._entities.append(obj) def search(self, keyobj): #returns an object with a specific key (keyobj) from the repo #raises a RepositoryError if the id is not in the repo if keyobj not in self._entities: raise RepositoryError(self._name + " Inexistent ID!\n") for obj in self._entities: if obj == keyobj: return obj def remove(self, obj): #removes an object from the repo #raises a RepositoryError if the obj does not exist i = 0 y = self.size() #print(self.size()) while i < self.size(): if self._entities[i] == obj: del self._entities[i] return i = i + 1 if y == self.size(): raise RepositoryError(self._name + " Inexistend ID!\n") def update(self, obj): #updates an object from the repo #raises a RepositoryError if the object does not exist for i in range(len(self._entities)): if self._entities[i] == obj: self._entities[i] = obj return raise RepositoryError(self._name + " Inexistend ID!\n") def get_all(self): #returns all the list from the repo return self._entities
def setUp(self): """ easier to init the values here than at every test methods """ #print('Initializing test and class instances') # creating the class instances self.dynArrayA = DynamicArray() self.dynArrayB = DynamicArray(size=3) # populating each instances self.dynArrayA.array[0:3] = [1,2,3]#np.arange(1,4) self.dynArrayB.array[0:3] = np.arange(1,4) # ensuring the index points to the right value self.dynArrayA.lastValueIndex = 3 self.dynArrayB.lastValueIndex = 3
def __init__(self, dataStructure): super(interactiveDataStructures, self).__init__() # rich module elements pretty.install() traceback.install() self.console = Console() # Datastructure elements availableDataStrutuces = { 'DynamicArray': DynamicArray(), 'SingleLinkedList': SinglyLinkedList(), 'DoublyLinkedList': DoublyLinkedList(), 'Stack': Stack(), 'Queue': Queue(), 'PriorityQueue': PriorityQueue() } correspondingNodes = { 'DynamicArray': None, 'SingleLinkedList': ListNode(None), 'DoublyLinkedList': ListNode(None), 'Stack': StackNode(None), 'Queue': QueueNode(None), 'PriorityQueue': PQNode(None) } if dataStructure in availableDataStrutuces: self.dataStructure = availableDataStrutuces[dataStructure] self.DSNode = correspondingNodes[dataStructure] self.DSname = dataStructure interactiveDataStructures.prompt = text.Text(f'({dataStructure}) ', style="bold magenta") # doesn't quite work else: raise ValueError(f'Please choose one of the following available data structure: {availableDataStrutuces.keys()}')
def __init__(self, Name, Table_Name): #self._conn = pymssql.connect('Trusted_Connection = yes', server = '(local)', user = '******', password = '******', database = 'Library') self._conn = pyodbc.connect( r'Driver={SQL Server};Server=DESKTOP-29D4507\SQLEXPRESS;Database=Library;Trusted_Connection = yes;' ) self._cursor = self._conn.cursor() self._name = Name self._table_name = Table_Name self._entities = DynamicArray()
def make_adj_list(self): adj = DynamicArray() for i in self.edge_list.array: if len(adj.array) < i.ori.id + 1: linklist1 = None else: linklist1 = adj.array[i.ori.id] if len(adj.array) < i.des.id + 1: linklist2 = None else: linklist2 = adj.array[i.des.id] if linklist1 is None: a = DList() a.Append(i.des) adj.dynamic_set(a, i.ori.id) else: linklist1.Append(i.des) if linklist2 is None: a = DList() a.Append(i.ori) adj.dynamic_set(a, i.des.id) else: linklist2.Append(i.ori) return adj
def radix_sort_int(sort_list, max): arr = DynamicArray(10) for i in range(len(arr.array)): arr.array[i] = DList() digit = 1 while digit <= max: print("================= Ordering by " + str(digit) + "'s ======================") for j in sort_list: arr.array[(j // digit) % 10].Append(x=j) i = 0 for k in arr.array: start = k.head if start is not None: while not k.IsEmpty(): print(start.data) temp = start.next sort_list[i] = k.Remove(start.data) start = temp i += 1 digit *= 10 return sort_list
def __init__(self, Name, filename, read_object, write_object): self._name = Name self._filename = filename self._read_object = read_object self._write_object = write_object self._entities = DynamicArray()
class FileRepo(): def __init__(self, Name, filename, read_object, write_object): self._name = Name self._filename = filename self._read_object = read_object self._write_object = write_object self._entities = DynamicArray() def read_all(self): self._entities = DynamicArray() with open(self._filename, "r") as f: lines = f.readlines() for line in lines: line = line.strip() if line != "": obj = self._read_object(line) self._entities.append(obj) def write_all(self): with open(self._filename, "w") as f: for obj in self._entities: line = self._write_object(obj) f.write(line + "\n") def size(self): #returns the size of the repo self.read_all() return len(self._entities) def add(self, obj): #adds a new object (obj) to the repo #raises a RepositoryError if the id of the obj is invalid self.read_all() if obj in self._entities: raise RepositoryError(self._name + " Existing ID!\n") self._entities.append(obj) self.write_all() def search(self, keyobj): #returns an object with a specific key (keyobj) from the repo #raises a RepositoryError if the id is not in the repo self.read_all() if keyobj not in self._entities: raise RepositoryError(self._name + " Inexistent ID!\n") for obj in self._entities: if obj == keyobj: return obj def remove(self, obj): #removes an object from the repo #raises a RepositoryError if the obj does not exist self.read_all() i = 0 y = self.size() #print(self.size()) while i < self.size(): if self._entities[i] == obj: del self._entities[i] self.write_all() return i = i + 1 if y == self.size(): raise RepositoryError(self._name + " Inexistend ID!\n") def update(self, obj): #updates an object from the repo #raises a RepositoryError if the object does not exist self.read_all() for i in range(len(self._entities)): if self._entities[i] == obj: self._entities[i] = obj self.write_all() return raise RepositoryError(self._name + " Inexistend ID!\n") def get_all(self): #returns all the list from the repo self.read_all() return self._entities
bos = Vertex(0, "Boston") seattle = Vertex(1, "Seattle") sf = Vertex(2, "San Francisco") denver = Vertex(3, "Denver") lv = Vertex(4, "Las Vegas") la = Vertex(5, "Los Angeles") minne = Vertex(6, "Minneapolis") dall = Vertex(7, "Dallas") dc = Vertex(8, "Wash DC") chic = Vertex(9, "Chicago") mia = Vertex(10, "Miami") ny = Vertex(11, "New York") vertex_list = [bos, seattle, sf, denver, lv, la, minne, dall, dc, chic, mia, ny] edge_list = DynamicArray() edge_list.dynamic_append(Edge(seattle, sf, 1306)) edge_list.dynamic_append(Edge(seattle, denver, 2161)) edge_list.dynamic_append(Edge(seattle, minne, 2661)) edge_list.dynamic_append(Edge(sf, la, 629)) edge_list.dynamic_append(Edge(sf, lv, 919)) edge_list.dynamic_append(Edge(lv, la, 435)) edge_list.dynamic_append(Edge(lv, denver, 1225)) edge_list.dynamic_append(Edge(lv, dall, 1983)) edge_list.dynamic_append(Edge(minne, chic, 661)) edge_list.dynamic_append(Edge(minne, denver, 1483)) edge_list.dynamic_append(Edge(minne, dall, 1532)) edge_list.dynamic_append(Edge(denver, dall, 1258)) edge_list.dynamic_append(Edge(dall, dc, 2113)) edge_list.dynamic_append(Edge(dall, mia, 2161)) edge_list.dynamic_append(Edge(dc, chic, 1145))
class FileRepo(): def __init__(self, Name, filename): self._name = Name self._filename = filename self._entities = DynamicArray() def read_bin_all(self): self._entities = DynamicArray() try: f = open(self._filename, 'rb') self._entities = pickle.load(f) except EOFError: self._entities = DynamicArray() def write_bin_all(self): f = open(self._filename, 'wb') pickle.dump(self._entities, f) f.close() def size(self): #returns the size of the repo return len(self._entities) def add(self, obj): #adds a new object (obj) to the repo #raises a RepositoryError if the id of the obj is invalid self.read_bin_all() if obj in self._entities: raise RepositoryError(self._name + " Existing ID!\n") self._entities.append(obj) self.write_bin_all() def search(self, keyobj): #returns an object with a specific key (keyobj) from the repo #raises a RepositoryError if the id is not in the repo self.read_bin_all() if keyobj not in self._entities: raise RepositoryError(self._name + " Inexistent ID!\n") for obj in self._entities: if obj == keyobj: return obj def remove(self, obj): #removes an object from the repo #raises a RepositoryError if the obj does not exist self.read_bin_all() i = 0 y = self.size() #print(self.size()) while i < self.size(): if self._entities[i] == obj: del self._entities[i] self.write_bin_all() return i = i + 1 if y == self.size(): raise RepositoryError(self._name + " Inexistend ID!\n") def update(self, obj): #updates an object from the repo #raises a RepositoryError if the object does not exist self.read_bin_all() for i in range(len(self._entities)): if self._entities[i] == obj: self._entities[i] = obj self.write_bin_all() return raise RepositoryError(self._name + " Inexistend ID!\n") def get_all(self): #returns all the list from the repo self.read_bin_all() return self._entities
def setUp(self): self.array = DynamicArray()
class DynamicArrayTest(unittest.TestCase): def setUp(self): self.array = DynamicArray() def test_get(self): with self.assertRaises(IndexError): self.array.get(2) self.array.get(-1) self.array.pushBack('a') self.array.pushBack('b') self.array.pushBack('c') self.assertEqual(self.array.get(1), 'b') self.assertEqual(self.array.get(0), 'a') self.assertEqual(self.array.get(2), 'c') with self.assertRaises(IndexError): self.array.get(3) def test_pushBack(self): self.array.pushBack(1) self.assertEqual(self.array.length(), 1) self.assertEqual(self.array.cap(), 1) self.array.pushBack(2) self.assertEqual(self.array.length(), 2) self.assertEqual(self.array.cap(), 2) self.array.pushBack(3) self.assertEqual(self.array.length(), 3) self.assertEqual(self.array.cap(), 4) self.array.pushBack(4) self.assertEqual(self.array.length(), 4) self.assertEqual(self.array.cap(), 4) self.array.pushBack(5) self.assertEqual(self.array.toString(), '1,2,3,4,5') self.assertEqual(self.array.length(), 5) self.assertEqual(self.array.cap(), 8) def test_set(self): with self.assertRaises(IndexError): self.array.set(0, 'a') self.array.set(-1, 'a') self.array.pushBack('a') self.array.pushBack('b') self.array.pushBack('c') self.array.set(1, 'b1') self.assertEqual(self.array.toString(), 'a,b1,c') self.array.set(0, 'a1') self.assertEqual(self.array.toString(), 'a1,b1,c') self.array.set(2, 'c1') self.assertEqual(self.array.toString(), 'a1,b1,c1') with self.assertRaises(IndexError): self.array.set(3, 'd') def test_remove(self): self.assertIsNone(self.array.remove(1)) self.assertIsNone(self.array.remove(-1)) self.array.pushBack('a') self.array.pushBack('b') self.array.pushBack('c') self.array.pushBack('d') self.array.pushBack('e') self.assertEqual(self.array.remove(0), 'a') self.assertEqual(self.array.remove(3), 'e') self.assertEqual(self.array.remove(2), 'd') self.assertEqual(self.array.remove(0), 'b') self.assertEqual(self.array.remove(0), 'c') self.assertIsNone(self.array.remove(0))
class JsonRepo(): def __init__(self, Name, filename, className): self._name = Name self._filename = filename self._classname = className self._entities = DynamicArray() def read_bin_all(self): self._entities = DynamicArray() with open(self._filename) as f: json_string = json.dumps(json.load(f), default=self.obj_to_dict, indent=2) self._entities = json.loads(json_string, object_hook=self._classname.as_obj) def write_bin_all(self): with open(self._filename, 'w') as f: json_string = json.dumps(self._entities, default=self.obj_to_dict, indent=2) f.write(json_string) def obj_to_dict(self, obj): if isinstance(obj, datetime.date): return { "_day": str(obj.day), "_month": str(obj.month), "_year": str(obj.year) } else: return obj.__dict__ def size(self): #returns the size of the repo return len(self._entities) def add(self, obj): #adds a new object (obj) to the repo #raises a RepositoryError if the id of the obj is invalid self.read_bin_all() if obj in self._entities: raise RepositoryError(self._name + " Existing ID!\n") self._entities.append(obj) self.write_bin_all() def search(self, keyobj): #returns an object with a specific key (keyobj) from the repo #raises a RepositoryError if the id is not in the repo self.read_bin_all() if keyobj not in self._entities: raise RepositoryError(self._name + " Inexistent ID!\n") for obj in self._entities: if obj == keyobj: return obj def remove(self, obj): #removes an object from the repo #raises a RepositoryError if the obj does not exist self.read_bin_all() i = 0 y = self.size() #print(self.size()) while i < self.size(): if self._entities[i] == obj: del self._entities[i] self.write_bin_all() return i = i + 1 if y == self.size(): raise RepositoryError(self._name + " Inexistend ID!\n") def update(self, obj): #updates an object from the repo #raises a RepositoryError if the object does not exist self.read_bin_all() for i in range(len(self._entities)): if self._entities[i] == obj: self._entities[i] = obj self.write_bin_all() return raise RepositoryError(self._name + " Inexistend ID!\n") def get_all(self): #returns all the list from the repo self.read_bin_all() return self._entities
def __init__(self, Name, filename): self._name = Name self._filename = filename self._entities = DynamicArray()
class RepositoryBooks(SQLRepo): def read_data(self): #reads all the data from the sql table self._entities = DynamicArray() cmd = 'SELECT * FROM ' + self._table_name self._cursor.execute(cmd) line = self._cursor.fetchone() while line is not None: obj = Book(int(line[0]), line[1], line[2]) self._entities.append(obj) line = self._cursor.fetchone() def get_all(self): #returns all the list from the repo self.read_data() return self._entities def add(self, obj): #adds a new object in the sql table cmd = "SELECT * FROM " + self._table_name + " WHERE Id=" + str( obj.bookID) + ";" #self.read_data() #if obj in self._entities: self._cursor.execute(cmd) line = self._cursor.fetchone() if line is not None: raise RepositoryError(self._name + " Existing ID!\n") cmd = 'INSERT INTO ' + self._table_name + " VALUES (" + str( obj.bookID) + ",'" + obj.bookTitle + "','" + obj.bookAuthor + "');" self._cursor.execute(cmd) self._conn.commit() def search(self, keyobj): #returns an object with a specific key (keyobj) from the repo #raises a RepositoryError if the id is not in the repo #print(str(keyobj.bookID)) cmd = "SELECT * FROM " + self._table_name + " WHERE Id=" + str( keyobj.bookID) + ";" self._cursor.execute(cmd) line = self._cursor.fetchone() if line is None: raise RepositoryError(self._name + " Inexistent ID!\n") return Book(int(line[0]), line[1], line[2]) def remove(self, obj): #removes an object from the repo #raises a RepositoryError if the obj does not exist b = self.search(obj) cmd = "DELETE FROM " + self._table_name + " WHERE Id=" + str( obj.bookID) + ";" self._cursor.execute(cmd) self._conn.commit() def update(self, obj): #updates an object from the repo #raises a RepositoryError if the object does not exist b = self.search(obj) cmd = "UPDATE " + self._table_name + " SET Title = '" + obj.bookTitle + "', Author = '" + obj.bookAuthor + "' WHERE Id=" + str( obj.bookID) + ";" self._cursor.execute(cmd) self._conn.commit() def searchBookId(self, bookId): self.read_data() l = [] for book in self._entities: if str(book.bookID).find(str(bookId)) != -1: l.append(book) if len(l) > 0: return l else: raise RepositoryError(self._name + " No matching books were found!\n") def searchBookAuthor(self, bookAuthor): self.read_data() l = [] for book in self._entities: if book.bookAuthor.lower().find(bookAuthor.lower()) != -1: l.append(book) if len(l) > 0: return l else: raise RepositoryError(self._name + " No matching books were found!\n") def searchBookTitle(self, bookTitle): self.read_data() l = [] for book in self._entities: if book.bookTitle.lower().find(bookTitle.lower()) != -1: l.append(book) if len(l) > 0: return l else: raise RepositoryError(self._name + " No matching books were found!\n") def get_all_authors(self): alist = [] cmd = "SELECT DISTINCT Author FROM " + self._table_name + ";" self._cursor.execute(cmd) line = self._cursor.fetchone() while line is not None: alist.append(line[0]) line = self._cursor.fetchone() return alist
from dynamicArray import DynamicArray from FileIo import FileIo from hashTable import HashTable print("Hashing Function 2") arr = DynamicArray() F = FileIo(filename="Customer.csv") table = HashTable(table=arr) F.file_io_chaining2(table) j = 0 print("%4s" % "No.", end=" ") print("%17s" % "Customer Id", end=" ") print("%14s" % "First Name", end=" ") print("%9s" % "Last Name") for i in range(len(table.table.array)): if table.table.array[i] is None: j += 1 if table.table.array[i] is not None: linkedlist = table.get_hashed(i) a = "[" + str(linkedlist.key) + "]" print("%4s" % a, end=" ") print("%17s" % linkedlist.head.data.customer_id, end=" ") print("%14s" % linkedlist.head.data.first_name, end=" ") print("%9s" % linkedlist.head.data.last_name, end=" ") if table.table.array[i].GetLength() > 1: start = linkedlist.head.next while start is not None: print("%17s" % start.data.customer_id, end=" ") print("%14s" % start.data.first_name, end=" ") print("%9s" % start.data.last_name, end=" ") start = start.next
class TestDynamicArray(unittest.TestCase): """ class that confirms the good working of the following method for the dynamic array class - search - deletion - insert - append - display """ def setUp(self): """ easier to init the values here than at every test methods """ #print('Initializing test and class instances') # creating the class instances self.dynArrayA = DynamicArray() self.dynArrayB = DynamicArray(size=3) # populating each instances self.dynArrayA.array[0:3] = [1,2,3]#np.arange(1,4) self.dynArrayB.array[0:3] = np.arange(1,4) # ensuring the index points to the right value self.dynArrayA.lastValueIndex = 3 self.dynArrayB.lastValueIndex = 3 def test_append(self): """ testing the appending function of the dynamicArray class method. Note that any changes in a test method doesn't affect """ print('testing appending method') # expected behavior resA = np.array([1,2,3,5,8,np.nan,np.nan,np.nan]) resB = np.array([1,2,3,5,8,np.nan]) # populating the arrays appendVal = [5,8] for val in appendVal: self.dynArrayA.append(val) self.dynArrayB.append(val) # try block to disply debug file when problems are encountered try: self.assertTrue(nan_equal(self.dynArrayA.array, resA)) self.assertTrue(nan_equal(self.dynArrayB.array, resB)) except AssertionError: print('error') logging.debug(f'testing appending method error. ArrayA:{self.dynArrayA.array}, ArrayB:{self.dynArrayB.array}') def test_delete(self): print('testing deletion method') # expected behavior resA = np.array([8,5,3,np.nan]) resB = np.array([3,2,np.nan]) #inserting vals to expand the bucket size before deletion to see appendVal = [5,8] for val in appendVal: self.dynArrayA.append(val) delVal=[1,2] for val in delVal: self.dynArrayA.delete(val) self.dynArrayB.delete(1) try: self.assertTrue(nan_equal(self.dynArrayA.array, resA)) self.assertTrue(nan_equal(self.dynArrayB.array, resB)) except AssertionError: print('error') logging.debug(f'testing deletion method error. ArrayA:{self.dynArrayA.array}, ArrayB:{self.dynArrayB.array}') def test_display(self): self.dynArrayA.display() self.dynArrayB.display() def test_insert(self): print('testing insert method') # expected behavior resA = np.array([8,5,3,2,1,np.nan,np.nan,np.nan]) resB = np.array([8,5,3,2,1,np.nan]) insertVal = [(5,1),(8,0)] for val,index in insertVal: self.dynArrayA.insert(val,index) self.dynArrayB.insert(val,index) try: self.assertTrue(nan_equal(self.dynArrayA.array, resA)) self.assertTrue(nan_equal(self.dynArrayB.array, resB)) except AssertionError: print('error') logging.debug(f'testing inser method error. ArrayA:{self.dynArrayA.array}, ArrayB:{self.dynArrayB.array}') def test_search(self): print('testing search method') # appending a single value to see if it will return the correct indexes self.dynArrayA.append(1) # expected behavior resA = [0,3] #1 resB = [1] #2 searchResA = self.dynArrayA.search(1) searchResB = self.dynArrayA.search(2) #print(f'expected Index:{resA} search res:{searchResA}\nexpected Index:{resB} search res:{searchResB}') try: self.assertEqual(resA,searchResA) self.assertEqual(resB,searchResB) except AssertionError: print('error') logging.debug(f'testing search method error. expected Index:{resA} search res:{searchResA} expected Index:{resB} search res:{searchResB}')