예제 #1
0
    def test_inf_queue(self):
        queue = ArrayQueue()
        queue.enqueue(1)
        queue.enqueue(2)
        assert queue.is_empty() == False
        assert queue.is_full() == False
        assert queue.capacity == float('inf')
        assert queue.__repr__() == 'ArrayQueue: front [1,2] tail'
        assert len(queue) == 2
        assert queue.front() == 1

        assert queue.dequeue() == 1
        assert queue.is_empty() == False
        assert queue.is_full() == False
        assert queue.capacity == float('inf')
        assert queue.__repr__() == 'ArrayQueue: front [2] tail'
        assert len(queue) == 1
        assert queue.front() == 2

        assert queue.dequeue() == 2
        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()
예제 #2
0
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()
예제 #3
0
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
예제 #4
0
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()
예제 #5
0
    def test_fix_len_queue(self):
        queue = ArrayQueue(3)
        queue.enqueue(1)
        queue.enqueue(2)
        assert queue.is_empty() == False
        assert queue.is_full() == False
        assert queue.capacity == 3
        assert queue.__repr__() == 'ArrayQueue: front [1,2] tail'
        assert len(queue) == 2
        assert queue.front() == 1

        queue.enqueue(3)
        assert queue.is_empty() == False
        assert queue.is_full() == True
        assert queue.capacity == 3
        assert queue.__repr__() == 'ArrayQueue: front [1,2,3] tail'
        assert len(queue) == 3
        assert queue.front() == 1
        with pytest.raises(FullError):
            queue.enqueue(4)

        assert queue.dequeue() == 1
        assert queue.is_empty() == False
        assert queue.is_full() == False
        assert queue.capacity == 3
        assert queue.__repr__() == 'ArrayQueue: front [2,3] tail'
        assert len(queue) == 2
        assert queue.front() == 2
예제 #6
0
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()
예제 #7
0
파일: tree.py 프로젝트: Wickan-lab/AADS
 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
예제 #8
0
    def test_fix_len_empty_queue(self):
        queue = ArrayQueue(0)
        assert queue.is_empty() == True
        assert queue.is_full() == True
        assert queue.capacity == 0
        assert queue.__repr__() == 'ArrayQueue: front [] tail'
        assert len(queue) == 0
        with pytest.raises(EmptyError):
            queue.front()
        with pytest.raises(EmptyError):
            queue.dequeue()
        with pytest.raises(FullError):
            queue.enqueue(1)

        queue = ArrayQueue(3)
        assert queue.is_empty() == True
        assert queue.is_full() == False
        assert queue.capacity == 3
        assert queue.__repr__() == 'ArrayQueue: front [] tail'
        assert len(queue) == 0
        with pytest.raises(EmptyError):
            queue.front()
        with pytest.raises(EmptyError):
            queue.dequeue()
예제 #9
0
​
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):
    AQ.dequeue()
end_time = time.time()
print(f"Array Queue time to dequeue: {end_time - start_time} seconds")
​
start_time = time.time()
for i in range(0, n):
    LLQ.dequeue()
end_time = time.time()
print(f"LLQueue time to dequeue: {end_time - start_time} seconds")
​
start_time = time.time()
for i in range(0, n):
    DQ.popleft()
end_time = time.time()
print(f"Deque time to dequeue: {end_time - start_time} seconds")
예제 #10
0
#       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())
    D.enqueue(D.dequeue())  # D = [1,2,3,5,4,6,7,8]

    for i in range(8):
        print(D.dequeue(), end=',')
예제 #11
0
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