示例#1
0
def hotPotato(namelist, numrounds):
    namequeue = Queue()
    for name in namelist:
        namequeue.enqueue(name)

    while namequeue.size() > 1:
        for i in range(numrounds):
            namequeue.enqueue(namequeue.dequeue())
        namequeue.dequeue()

    return namequeue.dequeue()
示例#2
0
def bfs(g, start):
    start.setDistance(0)
    start.setPred(None)
    vertQueue = Queue()
    vertQueue.enqueue(start)
    while vertQueue.size() > 0:
        currentVert = vertQueue.dequeue()
        for nbr in currentVert.getConnections():
            if nbr.getColor() == 'white':
                nbr.setColor('gray')
                nbr.setDistance(currentVert.getDistance() + 1)
                nbr.setPred(currentVert)
                vertQueue.enqueue(nbr)
        currentVert.setColor('black')
示例#3
0
def bfs(g, start):
    '''
    After running through BFS, all vertices of the graph will have their color, distance and predecessor from the start.
    '''
    start.set_predecessor(None)
    start.set_distance(0)
    vert_queue = Queue()
    vert_queue.enqueue(start)

    while vert_queue.size() != 0:
        cur_vertex = vert_queue.dequeue()

        for nbr in cur_vertex.get_connections():
            if nbr.color == Color.WHITE:
                nbr.set_color(Color.GRAY)
                nbr.set_distance(cur_vertex.get_distance() + 1)
                nbr.set_predecessor(cur_vertex)
                vert_queue.enqueue(nbr)

        cur_vertex.set_color(Color.BLACK)
示例#4
0
class MediaPlayer:
    def __init__(self):
        self.__mediaQueue = Queue()

    def addTrack(self, newTrack):
        self.__mediaQueue.enqueue(newTrack)

    def __str__(self):
        return str(self.__mediaQueue)

    @property        
    def count(self):
        return self.__mediaQueue.size()

    def play(self):
        while self.__mediaQueue.isEmpty() != False:
           currentTrack = self.__mediaQueue.dequeue() 
           print("Now playing",currentTrack) 
           sec = 1
           for s in currentTrack.length:
               time.sleep(1)
               print(sec," of ",currentTrack.length," seconds")
               sec += 1
        else:
            print("There are no tracks in the playlist")        

    def bringToFront(self, fronttrack):
        tracklist =  self.__mediaQueue
        newlist = Queue()
        found = False
        list2 = Queue()
        while not tracklist.isEmpty():
            first = tracklist.peek()
            if first != fronttrack:
                list2.addTrack(first)
                tracklist.dequeue()
            if first = fronttrack:
                found = True
                newlist.enqueue(first)
                tracklist.dequeue    
        else:
示例#5
0
class Handler:
    """ Handler class """

    _OPTIONS = {
        "1": "add_to_queue",
        "2": "remove_from_queue",
        "3": "get_first_item",
        "4": "get_queue_size",
        "5": "is_queue_empty",
        "q": "quit"
    }

    def __init__(self):
        """ Initialize class """
        self.queue = Queue()
        self.start()


    def _get_method(self, method_name):
        """
        Uses function getattr() to dynamically get value of an attribute.
        """
        return getattr(self, self._OPTIONS[method_name])


    def _print_menu(self):
        """
        Use docstring from methods to print options for the program.
        """
        menu = ""

        for key in sorted(self._OPTIONS):
            method = self._get_method(key)
            docstring = inspect.getdoc(method)

            menu += "{choice}: {explanation}\n".format(
                choice=key,
                explanation=docstring
            )

        print(chr(27) + "[2J" + chr(27) + "[;H")
        print(menu)

    def add_to_queue(self):
        """ Adds a node to the queue. """
        value = input("\nAdd a value: \n>>> ")
        self.queue.enqueue(value)
        print(f"{value} has been added.")

    def remove_from_queue(self):
        """ Removes the first node from the queue. """
        try:
            print(f"{self.queue.dequeue()} has been removed.")
        except EmptyQueueException as e:
            print(f"Error: {e}")

    def get_first_item(self):
        """ Prints the value of the first queue node. """
        try:
            print(self.queue.peek())
        except EmptyQueueException as e:
            print(f"Error: {e}")

    def get_queue_size(self):
        """ Shows the queue length. """
        print(self.queue.size())

    def is_queue_empty(self):
        """ Shows if the queue is empty or not. """
        print(self.queue.is_empty())

    @staticmethod
    def quit():
        """ Quit the program """
        sys.exit()

    def start(self):
        """ Start method """
        while True:
            self._print_menu()
            choice = input("Enter menu selection:\n-> ")

            try:
                self._get_method(choice.lower())()
            except KeyError:
                print("Invalid choice!")

            input("\nPress any key to continue ...")