def radixSort(a, x = 1): #runs a radix sort on an array #makes variables used later in the method cont = False next = 0 q = [ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue(), ArrayQueue()] #puts values from a in appropriate queues based on the current digit in the x place for i in a: if x < i: cont = True q[int((i%(10*x) - i%x)/x)].enqueue(i) #puts values in queues back into the array sorted by the appropriate number for i in q: while not i.is_empty(): a[next] = i.dequeue() next += 1 #does the recursive call or base case of the method if cont: return radixSort(a, 10*x) return a
def test_inf_empty_queue(self): queue = ArrayQueue() assert queue.is_empty() == True assert queue.is_full() == False assert queue.capacity == float('inf') assert queue.__repr__() == 'ArrayQueue: front [] tail' assert len(queue) == 0 with pytest.raises(EmptyError): queue.front() with pytest.raises(EmptyError): queue.dequeue()
class StockTracker: #set constructor as an empty object def __init__(self): self._total_qty = 0 self._profit = 0.0 self._arque = ArrayQueue() #buy stock. quantity must be greater than 0 and price must be a floating point number otherwise error occurs def buy ( self, quantity, price ): assert ( quantity > 0 ), 'quantity needs to be a positive integer' assert ( price > 0 ), 'price needs to be a positive floating point number' assert ( type( price ) is float ), 'price needs to be a positive floating point number' self._arque.enqueue( ( quantity, price ) ) self._total_qty += quantity #sell stock. quantity must be greater than 0, price must be floating point number, #quantity must be less than or equal to the quantity on hand other wise error occurs def sell ( self, quantity, price ): assert ( quantity > 0 ), 'quantity needs to be a positive integer' assert ( price > 0 ), 'price needs to be a positive floating point number' assert ( type( price ) is float ), 'type must be float' assert ( quantity <= self.getQuantityOnHand() ), 'quantity needs to be less than or equal to the total number of shares on hand' selling = 0 while quantity > 0: transaction = self._arque.dequeue() #Deque value amount = transaction[ 0 ] #Parse value value = transaction[ 1 ] if quantity >= amount: #Make sure the specific transaction has enough to fill the order selling += amount * ( price - value ) #Calculate the profit self._total_qty -= amount #Update remaining shares sell else: selling += quantity * ( price - value ) self._total_qty -= quantity self._arque.enqueue( ( amount - quantity, value ) ) #Re-add what is left of this transaction while self._arque.first() != ( amount - quantity, value ): #Send it back to the front self._arque.enqueue( self._arque.dequeue() ) quantity -= amount self._profit += selling return selling #returns total gain or loss since creating the empty object def getProfit (self): return self._profit #returns the quantity of shares on hand def getQuantityOnHand (self): return self._total_qty
def breadthfirst(self): """Generate a breadth-first iteration of the positions of the alberi.""" if not self.is_empty(): fringe = ArrayQueue() # known positions not yet yielded fringe.enqueue(self.root()) # starting with the root while not fringe.is_empty(): p = fringe.dequeue() # remove from front of the queue yield p # report this position for c in self.children(p): fringe.enqueue(c) # add children to back of queue
def main(): """Pulls data from file, assigns days and writes to submission file""" queue = ArrayQueue() cost = 0 assignments = [] days = {k: 0 for k in range(1, 101)} read_file("family_data.csv", queue) for i in range(2, 12): sort_list(queue, i) cost += first_pass(queue, days, assignments, i) while queue.first() != None: for i in range(2, 12): sort_list(queue, i) cost += single_pass(queue, days, assignments, i) cost += (days[100]-125.0) / 400.0 * days[100]**(0.5) cost += calc_accounting_penalty(days, 99, 100) write_file("submission_file.csv", assignments) print('${:.2f}'.format(cost))
def bfs_traversal(self): """implement a Breadth-First Search method inside the class Graph, use a FIFO queue rather than a level-by-level formulation to manage vertices that have been discovered until the time when their neighbors are considered. Return a map of vertices and the edges that those vertices are discovered. """ try: key, v = next(iter( self._outgoing.items())) #Gettig the starting key print("the starting vetrice = ", key) #displaying the starting vertice self.empty = ArrayQueue( ) #creating empty queue to enqueue and dequeue visited = [] #Empty list to keep track of the visited vertices visited.append(key) #Adding the starting Vertex to queue self.empty.enqueue( key) # Adding the starting Vertex to visited list print(key, " ", None) #The first vertice is visited by none while self.empty._size > 0: #checking the length of the queue key = self.empty.dequeue() #setting the pointer node for x in (self.incident_edges(key) ): #getting incident edges for vertex other_end = x.opposite( key) #getting the opposite vertice on that edge if other_end not in visited: #checking if the vertex has been visited print(other_end, " ", (key, other_end, x.element() )) #printing when the vertex was discovered self.empty.enqueue( other_end ) #appending the both the queue and cisited list visited.append(other_end) except TypeError: print("The vortex doesn't exit.")
def test_insert_two_then_remove(self): queue = ArrayQueue() queue.insert(1) queue.insert(2) res = queue.remove() self.assertEqual(res, 1) self.assertEqual(queue.list(), [2])
class ShopTracker: def __init__(self): self._listQueue = ArrayQueue() def startDay(self): """ Starts the day off by starting the listing process """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": self._listQueue.enqueue(alpha) alpha = raw_input("Please enter the name (Enter End when done): ") print len(self._listQueue) , "client(s) left" def addMore(self): """ Restarts the listing process again to add more names """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": alpha = raw_input("Please enter the name (Enter End when done): ") self._listQueue.enqueue(alpha) print len(self._listQueue) , "client(s) left" def endDay(self): """ Ends the day by clearing out the queue""" while len(self._listQueue) != 0: self._listQueue.dequeue() print len(self._listQueue) , "client(s) left" def getLength(self): """ Return length of elements in queue """ return len(self._listQueue) def primero(self): """ Prints out the first name in the queue (will not remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.first() def getNext(self): """ Return the first name in the queue (will remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.dequeue()
class ShopTracker: def __init__(self): self._listQueue = ArrayQueue() def startDay(self): """ Starts the day off by starting the listing process """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": self._listQueue.enqueue(alpha) alpha = raw_input("Please enter the name (Enter End when done): ") print len(self._listQueue), "client(s) left" def addMore(self): """ Restarts the listing process again to add more names """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": alpha = raw_input("Please enter the name (Enter End when done): ") self._listQueue.enqueue(alpha) print len(self._listQueue), "client(s) left" def endDay(self): """ Ends the day by clearing out the queue""" while len(self._listQueue) != 0: self._listQueue.dequeue() print len(self._listQueue), "client(s) left" def getLength(self): """ Return length of elements in queue """ return len(self._listQueue) def primero(self): """ Prints out the first name in the queue (will not remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.first() def getNext(self): """ Return the first name in the queue (will remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.dequeue()
def test4(): ct = ctypes.c_double*datasize Q = ArrayQueue(ct, 20) p = Process(target=operation4, args=(Q,)) p.start() data = ct() as_array(data)[:] = numpy.linspace(0,1,datasize) try: for i in xrange(reps): Q.put(data) finally: Q.close() p.join()
def array_queue(): return ArrayQueue()
def test_insert_until_full(self): queue = ArrayQueue(5) for i in range(5): queue.insert(i) self.assertEqual(queue.list(), [0, 1, 2, 3, 4])
def test_insert_to_full(self): queue = ArrayQueue(5) for i in range(5): queue.insert(i) with self.assertRaises(ValueError): queue.insert(5)
def __init__(self): self._listQueue = ArrayQueue()
def test_head_non_empty(self): queue = ArrayQueue() queue.insert(1) self.assertEqual(queue.head(), 1)
def test_is_empty_when_empty(self): queue = ArrayQueue() self.assertTrue(queue.isEmpty())
def test_is_empty_when_inserted_and_deleted(self): queue = ArrayQueue() queue.insert(1) queue.remove() self.assertTrue(queue.isEmpty())
def test_array_queue(): array_queue = ArrayQueue() # Assert that we start with an empty queue assert array_queue.is_empty() with pytest.raises(Empty): array_queue.first() # Enqueue a bunch of elements into the back of the queue for i in range(10): array_queue.enqueue(i) array_queue, first = array_queue.first() assert first == 0 assert len(array_queue) == i + 1 # Dequeue a bunch of elements from the front of the queue for i in range(10): array_queue, val = array_queue.dequeue() assert val == i assert len(array_queue) == 10 - 1 - i # Assert we are back to an empty queue assert array_queue.is_empty() with pytest.raises(Empty): array_queue.dequeue()
# Author: TianJun # E-mail: [email protected] # Website: www.tianjun.ml # # File Name: R6_13.py # Description: # use queue to change [1,2,3,4,5,6,7,8] into # [1,2,3,5,4,6,7,8] # Last Modified: # 2014-06-27 11:08:05 from array_queue import ArrayQueue if __name__ == '__main__': D = ArrayQueue() Q = ArrayQueue() #initial D for i in range(1, 9): D.enqueue(i) D.enqueue(D.dequeue()) D.enqueue(D.dequeue()) D.enqueue(D.dequeue()) # D = [4,5,6,7,8,1,2,3] Q.enqueue(D.dequeue()) # Q = [4], D = [5,6,7,8,1,2,3] D.enqueue(D.dequeue()) # Q = [4], D = [6,7,8,1,2,3,5] D.enqueue(Q.dequeue()) # Q = [], D = [6,7,8,1,2,3,5,4] D.enqueue(D.dequeue()) D.enqueue(D.dequeue())
from multiprocessing import Pipe, Process, Lock from array_queue import ArrayQueue import ctypes, numpy, os, time from numpy.ctypeslib import as_ctypes def operation(Q): data = as_ctypes(numpy.zeros(512, 'd')) pid = os.getpid() for i in xrange(3): Q.put(data) for i in xrange(10000): Q.put(data) j = Q.get() print len(j), pid return True if __name__ == "__main__": Q = ArrayQueue(ctypes.c_double * 512, 20) p1 = Process(target=operation, args=(Q, )) p2 = Process(target=operation, args=(Q, )) p1.start() p2.start() p1.join() p2.join()
for i in range(TEST_NUM // 2): deque.pop_tail() for i in range(TEST_NUM // 2): deque.pop_front() end = time.time() return end - start if __name__ == '__main__': print('TEST_NUM: {}'.format(TEST_NUM)) queue = ArrayQueue(TEST_NUM) print('ArrayQueue, time: {:.3f} s'.format(queue_exec_time(queue))) queue = LinkedListQueue(TEST_NUM) print('LinkedListQueue, time: {:.3f} s'.format(queue_exec_time(queue))) queue = ArrayLoopQueue(TEST_NUM) print('ArrayLoopQueue, time: {:.3f} s'.format(queue_exec_time(queue))) queue = LinkedListLoopQueue(TEST_NUM) print('LinkedListLoopQueue, time: {:.3f} s'.format(queue_exec_time(queue))) deque = ArrayDeque(TEST_NUM) print('ArrayDeque, time: {:.3f} s'.format(deque_exec_time(deque))) deque = LinkedListDeque(TEST_NUM)
def __init__(self): self._total_qty = 0 self._profit = 0.0 self._arque = ArrayQueue()
class ArrayQueue: """FIFO queue implementation using a Python list as underlying storage.""" dc = 3 # moderate capacity for all new queues def __init__(self): """Create an empty queue.""" self._data = [None] * ArrayQueue.dc self._size = 0 self._front = 0 def __len__(self): """Return the number of elements in the queue.""" return self._size def is_empty(self): """Return True if the queue is empty.""" return self._size == 0 def first(self): """Return (but do not remove) the element at the front of the queue. Raise Empty exception if the queue is empty. """ if self.is_empty(): raise Exception('Queue is empty') return self._data[self._front] def dequeue(self): """Remove and return the first element of the queue (i.e., FIFO). Raise Empty exception if the queue is empty. """ if self.is_empty(): raise Exception('Queue is empty') answer = self._data[self._front] self._data[self._front] = None # help garbage collection self._front = (self._front + 1) % len(self._data) self._size -= 1 return answer def enqueue(self, e): """Add an element to the back of queue.""" if self._size == len(self._data): self._resize(2 * len(self.data)) # double the array size avail = (self._front + self._size) % len(self._data) self._data[avail] = e self._size += 1 def _resize(self, cap): # we assume cap >= len(self) """Resize to a new list of capacity >= len(self).""" old = self._data # keep track of existing list self._data = [None] * cap # allocate list with new capacity walk = self._front for k in range(self._size): # only consider existing elements self._data[k] = old[k] #self._data[k] = old[walk] # intentionally shift indices walk = (1 + walk) % len(old) # use old size as modulus self._front = 0 # front has been realigned if __name__ == '__main__': from array_queue import ArrayQueue Q = ArrayQueue() # contents: [ ] Q.enqueue(1) Q.enqueue(2) Q._resize(3)
def test_remove_empty(self): queue = ArrayQueue() with self.assertRaises(ValueError): res = queue.remove()
def test_array_queue_constructor(): aq1 = ArrayQueue() assert len(aq1._array) == 10 aq2 = ArrayQueue(20) assert len(aq2._array) == 20
def test_insert_one(self): queue = ArrayQueue() queue.insert(1) self.assertEqual(queue.list(), [1])
def test_insert_two(self): queue = ArrayQueue() queue.insert(1) queue.insert(2) self.assertEqual(queue.list(), [1, 2])
def test_is_empty_when_inserted(self): queue = ArrayQueue() queue.insert(1) self.assertFalse(queue.isEmpty())
def test_head_empty(self): queue = ArrayQueue() with self.assertRaises(ValueError): queue.head()
import time from ll_queue import LLQueue from array_queue import ArrayQueue from collections import deque n = 100000 AQ = ArrayQueue() LLQ = LLQueue() DQ = deque() start_time = time.time() for i in range(0, n): AQ.enqueue(i) end_time = time.time() print(f"Array Queue time to enqueue: {end_time - start_time} seconds") start_time = time.time() for i in range(0, n): LLQ.enqueue(i) end_time = time.time() print(f"LLQueue time to enqueue: {end_time - start_time} seconds") start_time = time.time() for i in range(0, n): DQ.append(i) end_time = time.time() print(f"Deque time to enqueue: {end_time - start_time} seconds") start_time = time.time() for i in range(0, n):
class Graph: """Representation of a simple graph using an adjacency map.""" #------------------------- nested Vertex class ------------------------- class Vertex: """Lightweight vertex structure for a graph.""" __slots__ = '_element' def __init__(self, x): """Do not call constructor directly. Use Graph's insert_vertex(x).""" self._element = x def element(self): """Return element associated with this vertex.""" return self._element def __hash__(self): # will allow vertex to be a map/set key return hash(id(self)) def __str__(self): return str(self._element) def __eq__(self, other): return str(self) == str(other) def __repr__(self): return str(self._element) #------------------------- nested Edge class ------------------------- class Edge: """Lightweight edge structure for a graph.""" __slots__ = '_origin', '_destination', '_element' def __init__(self, u, v, x): """Do not call constructor directly. Use Graph's insert_edge(u,v,x).""" self._origin = u self._destination = v self._element = x def endpoints(self): """Return (u,v) tuple for vertices u and v.""" return (self._origin, self._destination) def opposite(self, v): """Return the vertex that is opposite v on this edge.""" if not isinstance(v, Graph.Vertex): raise TypeError('v must be a Vertex') return self._destination if v is self._origin else self._origin raise ValueError('v not incident to edge') def element(self): """Return element associated with this edge.""" return self._element def __hash__(self): # will allow edge to be a map/set key return hash((self._origin, self._destination)) def __str__(self): return '({0},{1},{2})'.format(self._origin, self._destination, self._element) def __eq__(self, other): return str(self) == str(other) def __repr__(self): return '({0},{1},{2})'.format(self._origin, self._destination, self._element) #------------------------- Graph methods ------------------------- def __init__(self, directed=False): """Create an empty graph (undirected, by default). Graph is directed if optional paramter is set to True. """ self._outgoing = {} # only create second map for directed graph; use alias for undirected self._incoming = {} if directed else self._outgoing self.directed = directed def _validate_vertex(self, v): """Verify that v is a Vertex of this graph.""" if not isinstance(v, self.Vertex): raise TypeError('*Vertex expected') if v not in self._outgoing: raise ValueError('*Vertex does not belong to this graph.') def _validate_edge(self, e): #validating the edge """Verify that e is an Edge of this graph.""" if not isinstance(e, self.Edge): raise TypeError('*Edge expected') def is_directed(self): """Return True if this is a directed graph; False if undirected. Property is based on the original declaration of the graph, not its contents. """ return self._incoming is not self._outgoing # directed if maps are distinct def vertex_count(self): """Return the number of vertices in the graph.""" return len(self._outgoing) def vertices(self): """Return an iteration of all vertices of the graph.""" return self._outgoing.keys() def edge_count(self): """Return the number of edges in the graph.""" total = sum(len(self._outgoing[v]) for v in self._outgoing) # for undirected graphs, make sure not to double-count edges return total if self.is_directed() else total // 2 def edges(self): """Return a set of all edges of the graph.""" result = set() # avoid double-reporting edges of undirected graph for secondary_map in self._outgoing.values(): result.update(secondary_map.values()) # add edges to resulting set return result def get_edge(self, u, v): """Return the edge from u to v, or None if not adjacent.""" self._validate_vertex(u) self._validate_vertex(v) return self._outgoing[u].get(v) # returns None if v not adjacent def degree(self, v, outgoing=True): """Return number of (outgoing) edges incident to vertex v in the graph. If graph is directed, optional parameter used to count incoming edges. """ self._validate_vertex(v) adj = self._outgoing if outgoing else self._incoming return len(adj[v]) def incident_edges(self, v, outgoing=True): """Return all (outgoing) edges incident to vertex v in the graph. If graph is directed, optional parameter used to request incoming edges. """ self._validate_vertex(v) adj = self._outgoing if outgoing else self._incoming for edge in adj[v].values(): yield edge def insert_vertex(self, x=None): """Insert and return a new Vertex with element x.""" v = self.Vertex(x) self._outgoing[v] = {} if self.is_directed(): self._incoming[v] = {} # need distinct map for incoming edges return v def insert_edge(self, u, v, x=None): """Insert and return a new Edge from u to v with auxiliary element x. Raise a ValueError if u and v are not vertices of the graph. Raise a ValueError if u and v are already adjacent. """ if self.get_edge(u, v) is not None: # includes error checking raise ValueError('u and v are already adjacent') e = self.Edge(u, v, x) self._outgoing[u][v] = e self._incoming[v][u] = e def remove_vertex(self, v): """Remove the vertex v and all its incident edges, and return the vertex been removed. Parameter v is an instance of Vertex Algorithm should run in O(deg(v)) time """ self._validate_vertex(v) #validating vertex u edges = list(self.incident_edges(v, False)) if self.directed else list( self.incident_edges(v)) for edge in edges: #deleting incident edges of v self.remove_edge(edge) #removing each edge del self._outgoing[v] #deleting the vertex return v def remove_edge(self, e): """remove the edge e from the adjacency map for each incident vertex, and return the edge removed. Parameter e is an instance of Edge Algorithm should run in O(1) time. """ self._validate_edge(e) #validating the receive edge u, v = e.endpoints() #getting the endpoints from edge instance self._validate_vertex(u) #validating vertex u self._validate_vertex(v) #validating vertex v #deleting the v to u edge if it undirected graph, and if edge v to u exists on this undirected graph if not self.directed and self._outgoing[v][u]: del self._outgoing[v][u] del self._outgoing[u][v] #deleting the edge received return e def bfs_traversal(self): """implement a Breadth-First Search method inside the class Graph, use a FIFO queue rather than a level-by-level formulation to manage vertices that have been discovered until the time when their neighbors are considered. Return a map of vertices and the edges that those vertices are discovered. """ try: key, v = next(iter( self._outgoing.items())) #Gettig the starting key print("the starting vetrice = ", key) #displaying the starting vertice self.empty = ArrayQueue( ) #creating empty queue to enqueue and dequeue visited = [] #Empty list to keep track of the visited vertices visited.append(key) #Adding the starting Vertex to queue self.empty.enqueue( key) # Adding the starting Vertex to visited list print(key, " ", None) #The first vertice is visited by none while self.empty._size > 0: #checking the length of the queue key = self.empty.dequeue() #setting the pointer node for x in (self.incident_edges(key) ): #getting incident edges for vertex other_end = x.opposite( key) #getting the opposite vertice on that edge if other_end not in visited: #checking if the vertex has been visited print(other_end, " ", (key, other_end, x.element() )) #printing when the vertex was discovered self.empty.enqueue( other_end ) #appending the both the queue and cisited list visited.append(other_end) except TypeError: print("The vortex doesn't exit.") def print_graph(self): """this method should print all vertices with their incident edges. """ if len(self._outgoing) > 0: for key, nested in self._outgoing.items(): print(key, list(nested.values())) else: raise ValueError