class Solution_32b(object):
    def __init__(self):
        self.queue = LinkedQueue()

    def print_tree(self, treeroot):
        if treeroot is None:
            return

        self.queue.add(treeroot)

        nextlevel, tobeprinted = 0, 1

        print('Print the tree structure by level.')
        while not self.queue.isEmpty():
            pnode = self.queue.peek()
            print('%d' % pnode.data_, end=' | ')
            if pnode.left_ is not None:
                self.queue.add(pnode.left_)
                nextlevel += 1
            if pnode.right_ is not None:
                self.queue.add(pnode.right_)
                nextlevel += 1
            self.queue.pop()
            tobeprinted -= 1
            if tobeprinted == 0:
                print('\n')
                tobeprinted = nextlevel
                nextlevel = 0
Ejemplo n.º 2
0
class TicketCounterSimulation:
    # Create a simulation object.
    def __init__(self, numAgents, numMinutes, betweenTime, serviceTime):
        # Parameters supplied by the user.
        self._arriveProb = 1.0 / betweenTime
        self._serviceTime = serviceTime
        self._numMinutes = numMinutes

        # Simulation components.
        self._passengerQ = Queue()
        self._theAgents = Array(numAgents)
        for i in range(numAgents):
            self._theAgents[i] = TicketAgent(i + 1)

        # Computed during the simulation.
        self._totalWaitTime = 0
        self._numPassengers = 0

    # Run the simulation using the parameters supplied earlier.
    def run(self):
        for curTime in range(self._numMinutes + 1):
            self._handleArrive(curTime)
            self._handleBeginService(curTime)
            self._handleEndService(curTime)
        self.printResults()

    # Print the simulation results.
    def printResults(self):
        numServed = self._numPassengers - len(self._passengerQ)
        avgWait = float(self._totalWaitTime) / numServed
        print("")
        print("Number of passengers served = ", numServed)
        print("Number of passengers remaining in line = %d" %
              len(self._passengerQ))
        print("The average wait time was %4.2f minutes." % avgWait)

    # Handles simulation rule #1.
    def _handleArrive(self, curTime):
        if random.randint(0.0, 1.0) <= self._arriveProb:
            self._numPassengers += 1
            passenger = Passenger(self._numPassengers, curTime)
            self._passengerQ.add(passenger)

    # Handles simulation rule #2.
    def _handleBeginService(self, curTime):
        for agent in self._theAgents:
            if agent.isFree():
                if not self._passengerQ.isEmpty():
                    agent.startService(self._passengerQ.pop(),
                                       curTime + self._serviceTime)

    # Handles simulation rule #3.
    def _handleEndService(self, curTime):
        for agent in self._theAgents:
            if agent.isFinished(curTime):
                passenger = agent.stopService()
        self._totalWaitTime += len(self._passengerQ)
Ejemplo n.º 3
0
class Cashier(object):
    """Represents a cashier."""

    def __init__(self):
        """Maintains a queue of customers,
        number of customers served, total customer wait time,
        and a current customer being processed."""
        self._totalCustomerWaitTime = 0
        self._customersServed = 0
        self._currentCustomer = None
        self._queue = LinkedQueue()

    def addCustomer(self, c):
        """Adds an arriving customer to my line."""
        self._queue.add(c)
   
    def serveCustomers(self, currentTime):
        """Serves my cuatomers during a given unit of time."""
        if self._currentCustomer is None:
            # No customers yet
            if self._queue.isEmpty():
                return
            else:
                # Pop first waiting customer and tally results
                self._currentCustomer = self._queue.pop()
                self._totalCustomerWaitTime += \
                                            currentTime - \
                                            self._currentCustomer.arrivalTime()
                self._customersServed += 1

        # Give a unit of service
        self._currentCustomer.serve()

        # If current customer is finished, send it away   
        if self._currentCustomer.amountOfServiceNeeded() == 0:
            self._currentCustomer = None
   
    def __str__(self):
        """Returns my results: my total customers served,
        my average wait time per customer, and customers left on my queue."""
        result = "TOTALS FOR THE CASHIER\n" + \
                 "Number of customers served:        " + \
                 str(self._customersServed) + "\n"
        if self._customersServed != 0:
            aveWaitTime = self._totalCustomerWaitTime /\
                          self._customersServed
            result += "Number of customers left in queue: " + \
                      str(len(self._queue)) + "\n" + \
                      "Average time customers spend\n" + \
                      "waiting to be served:              " + \
                      "%5.2f" % aveWaitTime
        return result
Ejemplo n.º 4
0
class Cashier(object):
    """Represents a cashier."""
    def __init__(self, number):
        """Maintains a cashier number, a queue of customers,
        number of customers served, total customer wait time,
        and a current customer being processed."""
        self._number = number
        self._totalCustomerWaitTime = 0
        self._customersServed = 0
        self._currentCustomer = None
        self._queue = LinkedQueue()

    def getLineLength(self):
        """Returns the number of customers in the line."""
        return len(self._queue)

    def addCustomer(self, c):
        """Adds an arriving customer to my line."""
        self._queue.add(c)

    def serveCustomers(self, currentTime):
        """Serves my cuatomers during a given unit of time."""
        if self._currentCustomer is None:
            # No customers yet
            if self._queue.isEmpty():
                return
            else:
                # Pop first waiting customer and tally results
                self._currentCustomer = self._queue.pop()
                self._totalCustomerWaitTime += \
                                            currentTime - \
                                            self._currentCustomer.arrivalTime()
                self._customersServed += 1

        # Give a unit of service
        self._currentCustomer.serve()

        # If current customer is finished, send it away
        if self._currentCustomer.amountOfServiceNeeded() == 0:
            self._currentCustomer = None

    def __str__(self):
        """Returns my results: my number, my total customers served,
        my average wait time per customer, and customers left on my queue."""
        if self._customersServed != 0:
            aveWaitTime = float(self._totalCustomerWaitTime) /\
                          self._customersServed
        else:
            aveWaitTime = 0.0
        result = "%4d %8d %13.2f %8d" % (self._number, self._customersServed,
                                         aveWaitTime, len(self._queue))
        return result
def bfs(g, start):
    start.setDistance(0)
    start.setPred(None)
    vertQueue = LinkedQueue()
    vertQueue.add(start)
    while not vertQueue.isEmpty():
        currentVert = vertQueue.pop()
        for nbr in currentVert.getConnections():
            if (nbr.getColor()) == 'white':
                nbr.setColor('gray')
                nbr.setDistance(currentVert.getDistance() + 1)
                nbr.setPred(currentVert)
                vertQueue.add(nbr)
        currentVert.setColor('black')
Ejemplo n.º 6
0
 def levelorder(self):
     """Supports a levelorder traversal on a view of self."""
     lyst = list()
     queue = LinkedQueue()
     if not self.isEmpty():
         queue.add(self.root)
     while not queue.isEmpty():
         node = queue.pop()
         lyst.append(node.data)
         if node.left != None:
             queue.add(node.left)
         if node.right != None:
             queue.add(node.right)
     return iter(lyst)
Ejemplo n.º 7
0
class Cashier(object):
    def __init__(self):
        self._total_customer_wait_time = 0
        self._customers_served = 0
        self._current_customer = None
        self._queue = LinkedQueue()

    def add_customer(self, c):
        self._queue.add(c)

    def serve_customers(self, current_time):
        # 1. 当前顾客不存在,
        if self._current_customer == None:
            # 等待队列为空, 直接返回
            if self._queue.isEmpty():
                return
            else:  # 不为空, 将队头顾客提升为当前顾客
                self._current_customer = self._queue.pop()
                # 等待总时间加上当前顾客等待的时间
                self._total_customer_wait_time += \
                    current_time - \
                    self._current_customer.arrival_time()
                self._customers_served += 1

        # 2. 给当前顾客一个单位服务
        self._current_customer.serve()

        # 如果当前顾客需要的单位服务已经满足, 则将当前顾客赋值为 None
        if self._current_customer.amount_of_service_needed() == 0:
            self._current_customer = None

    def __str__(self):
        """
        Returns my results: my total customers served,
        my average wait time per customer, and customers left on my queue.
        """
        result = "TOTALS FOR THE CASHIER\n" + \
                 "Number of customers served:        " + \
                 str(self._customers_served) + "\n"
        if self._customers_served != 0:
            ave_wait_time = self._total_customer_wait_time /\
                          self._customers_served
            result += "Number of customers left in queue: " + \
                      str(len(self._queue)) + "\n" + \
                      "Average time customers spend\n" + \
                      "waiting to be served:              " + \
                      "%5.2f" % ave_wait_time
        return result
Ejemplo n.º 8
0
def breadthFirst(g, startLabel):
    """Returns a list of the vertex labels in the
    order in which the vertices were visited."""
    result = list()
    g.clearVertexMarks()
    queue = LinkedQueue()
    queue.add(g.getVertex(startLabel))
    while not queue.isEmpty():
        vertex = queue.pop()
        if not vertex.isMarked():
            vertex.setMark()
            result.append(vertex.getLabel())
            for neighbor in g.neighboringVertices(vertex.getLabel()):
                if not neighbor.isMarked():
                    queue.add(neighbor)
    return result
Ejemplo n.º 9
0
class Cashier(object):
    def __init__(self):
        """

        """
        self._totalCustomerWaitTime = 0
        self._customersServed = 0
        self._currentCustomer = None
        self._queue = LinkedQueue()

    def addCustomer(self, c):
        self._queue.add(c)

    def serveCustomers(self, currentTime):
        """

        :param currentTime:
        :type currentTime:
        :return:
        :rtype:
        """
        if self._currentCustomer is None:
            # No customers yet
            if self._queue.isEmpty():
                return
            else:
                # Pop first waiting customer and tally results
                self._currentCustomer = self._queue.pop()
                self._totalCustomerWaitTime += currentTime - self._currentCustomer.arrivalTime(
                )
                self._customersServed += 1
        # Give a unit of service
        self._currentCustomer.serve()
        # If current customer is finished, send it away
        if self._currentCustomer.amountOfServiceNeeded() == 0:
            self._currentCustomer = None

    def __str__(self):
        result = "TOTALS FOR THE CASHIER\n" + "Number of customers served: " + \
                str(self._customersServed) + "\n"
        if self._customersServed != 0:
            aveWaitTime = self._totalCustomerWaitTime / self._customersServed
            result += "Number of customers left in queue: " \
            + str(len(self._queue)) + "\n" + "Average time customers spend\n" + \
            "waiting to be served: " + "%5.2f" % aveWaitTime
        return result
Ejemplo n.º 10
0
class Solution_32(object):
    def __init__(self):
        self.queue = LinkedQueue()

    def printfromtoptobottom(self, treeroot):
        if treeroot is None:
            return None

        self.queue.add(treeroot)
        ret = []
        while not self.queue.isEmpty():
            node = self.queue.pop()
            ret.append(node.data_)
            if node.left_:
                self.queue.add(node.left_)
            if node.right_:
                self.queue.add(node.right_)
        return ret
Ejemplo n.º 11
0
class Stack(object):
    def __init__(self):
        self.stack1 = LinkedQueue()
        self.stack2 = LinkedQueue()

    def isEmpty(self):
        if self.__len__() == 0:
            return True
        else:
            return False

    def __len__(self):
        if self.stack1.size_ == 0:
            return self.stack2.size_
        else:
            return self.stack1.size_

    def peek(self):
        if self.isEmpty():
            raise KeyError('The stack is empty.')
        elif not self.stack1.isEmpty():
            item = self.stack1.peek()
            return item
        else:
            item = self.stack2.peek()
            return item

    def push(self, item):
        if self.isEmpty() or (not self.stack1.isEmpty()
                              and self.stack2.isEmpty()):
            self.stack1.add(item)
        else:
            self.stack2.add(item)

    def pop(self):
        if self.isEmpty():
            raise KeyError('The stack is empty.')
        if not self.stack1.isEmpty():
            while self.stack1.front_.next is not None:
                self.stack2.add(self.stack1.pop())
            item = self.stack1.pop()
            return item
        else:
            while self.stack2.front_.next is not None:
                self.stack1.add(self.stack2.pop())
            item = self.stack2.pop()
            return item

    # def __iter__(self):
    #     def travser_stack_recursive(sta, templist):
    #         if sta.front_.next is not None:
    #             templist = travser_stack_recursive(sta.front_.next, templist)
    #         templist.append(sta.front_.data)
    #         return templist
    #
    #     templist = list()
    #     if self.isEmpty():
    #         raise KeyError('The stack is empty.')
    #
    #     if not self.stack1.isEmpty():
    #         travser_stack_recursive(self.stack1, templist)
    #         return iter(templist)
    #     else:
    #         travser_stack_recursive(self.stack2, templist)
    #         return iter(templist)

    def __iter__(self):
        if self.isEmpty():
            raise KeyError('The stack is empty.')
        templist = list()
        if not self.stack1.isEmpty():
            tempstack = copy.copy(self.stack1)
            while tempstack.front_.next is not None:
                templist.append(tempstack.pop())
            templist.append(tempstack.pop())
            templist.reverse()  # ******
            return iter(templist)
        else:
            tempstack = copy.copy(self.stack2)
            while tempstack.front_.next is not None:
                templist.append(tempstack.pop())
            templist.append(tempstack.pop()).reverse()
            templist.reverse()  # ******
            return iter(templist)