• Understanding Data Sorting and Types in Python - Part 4

    Working with queues


    A queue works differently from a stack. Think of any line you’ve ever stood in: You go to the back of the line, and when you reach the front of the line you get to do whatever you stood in the line to do. A queue is often used for task scheduling and to maintain program flow — just as it is in the real world. The following steps help you create a queue-based application.
     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    import queue

    MyQueue = queue.Queue(3)

    print(MyQueue.empty())
    input("Press any key when ready...")


    MyQueue.put(1)
    MyQueue.put(2)
    print(MyQueue.full())
    input("Press any key when ready...")

    MyQueue.put(3)
    print(MyQueue.full())
    input("Press any key when ready...")

    print(MyQueue.get())
    print(MyQueue.empty())
    print(MyQueue.full())
    input("Press any key when ready...")

    print(MyQueue.get())
    print(MyQueue.get())

    To create a queue, you must import the queue module. This module actually contains a number of queue types, but this example uses only the standard FIFO queue.

    When a queue is empty, the empty() function returns True. Likewise, when a queue is full, the full() function returns True. By testing the state of empty() and full(), you can determine whether you need to perform additional work with the queue or whether you can add other information to it. These two functions help you manage a queue . It’s not possible to iterate through a queue using a for loop as you have done with other collection types, so you must monitor empty() and full() instead.

    The two functions used to work with data in a queue are put(), which adds new data, and get(), which removes data. A problem with queues is that if you try to put more items into the queue than it can hold, it simply waits until space is available to hold it. Unless you’re using a multithreaded application (one that uses individual threads of execution to perform more than one task at one time), this state could end up freezing your application.

     Choose RunRun Module.

    You see a Python Shell window open. The application tests the state of the queue. In this case, you see an output of True, which means that the queue is empty.

     Press Enter.

    The application adds two new values to the queue. In doing so, the queue is no longer empty.


     Press Enter.

    The application adds another entry to the queue, which means that the queue is now full because it was set to a size of 3. This means that full() will return True because the queue is now full.

     Press Enter.

    To free space in the queue, the application gets one of the entries. Whenever an application gets an entry, the get() function returns that entry. Given that 1 was the first value added to the queue, the print() function should return a value of 1,. In addition, both empty() and full() should now return False.




     Press Enter.

    The application gets the remaining two entries. You see 2 and 3 (in turn) as output.


    Working with deques


    A deque is simply a queue where you can remove and add items from either end. In many languages, a queue or stack starts out as a deque. Specialized code serves to limit deque functionality to what is needed to perform a particular task.

    When working with a deque, you need to think of the deque as a sort of horizontal line. Certain individual functions work with the left and right ends of the deque so that you can add and remove items from either side. The following steps help you create an example that demonstrates deque usage.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line.

    import collections

    MyDeque = collections.deque("abcdef", 10)

    print("Starting state:") for Item in MyDeque:

    print(Item, end=" ")

    print("\r\n\r\nAppending and extending right") MyDeque.append("h")
    MyDeque.extend("ij") for Item in MyDeque:

    print(Item, end=" ") print("\r\nMyDeque contains {0} items."
    .format(len(MyDeque)))

    print("\r\nPopping right")

    print("Popping {0}".format(MyDeque.pop())) for Item in MyDeque:
    print(Item, end=" ")

    print("\r\n\r\nAppending and extending left") MyDeque.appendleft("a") MyDeque.extendleft("bc")
    for Item in MyDeque: print(Item, end=" ")
    print("\r\nMyDeque contains {0} items."
    .format(len(MyDeque)))


    print("\r\nPopping left")
    print("Popping {0}".format(MyDeque.popleft())) for Item in MyDeque:
    print(Item, end=" ")

    print("\r\n\r\nRemoving")
    MyDeque.remove("a") for Item in MyDeque:
    print(Item, end=" ")

    The implementation of deque is found in the collections module, so you need to import it into your code. When you create a deque, you can optionally specify a starting list of iterable items (items that can be accessed and processed as part of a loop structure) and a maximum size, as shown.

    A deque differentiates between adding one item and adding a group of items. You use append() or appendleft() when adding a single item. The extend() and extendleft() functions let you add multiple items. You use the pop() or popleft() functions to remove one item at a time. The act of popping values returns the value popped, so the example prints the value onscreen. The remove() function is unique in that it always works from the left side and always removes the first instance of the requested data.

    Unlike some other collections, a deque is fully iterable. This means that you can obtain a list of items using a for loop whenever necessary.

    3. Choose RunRun Module.

    You see a Python Shell window open.


    It’s important to follow the output listing closely. Notice how the size of the deque changes over time. After the application pops the j, the deque still contains eight items. When the application appends and extends from the left, it adds three more items. However, the resulting deque contains only ten items. When you exceed the maximum size of a deque, the extra data simply falls off the other e
  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts