A queue is a data structure that is based on the FIFO (first in, first out) principle. Items that are appended to the queue are also removed in that same order.
Think of an actual queue formed when people wait in line for something. People who join the queue first also get their turn first. The data structure queue operates in the same manner.
A queue can be utilized to print binary numbers using the following algorithm:
Enqueue the first binary number 1 to the queue.
While the desired number of binary numbers have not been printed:
Dequeue an item from the queue.
Print the dequeued item.
Append 0 to the dequeued item, and enqueue the resulting string back to the queue.
Append 1 to the dequeued item, and enqueue the resulting string back to the queue.
Note:
Each dequeued item is used to generate two new binary numbers.
We implement the numbers we are printing as strings, which allows appending 0 and 1 to the dequeued number.
Let’s implement the algorithm discussed in Python in the following manner.
Click the “Run” button to execute the code example:
import queuedef print_binary(num):# creating a queueq = queue.Queue()# enqueuing the first binary numberq.put('1')while(num > 0):# Dequeuing and printing itemitem = q.get()print(item)# enqueueing two more numbersq.put(item + '0')q.put(item + '1')num = num - 1if __name__ == "__main__":print_binary(10)
Let's breakdown the code given above:
Lines 3–19: We implement a function print_binary
that takes as input num
, which dictates how many binary numbers should be printed:
Line 5: We create a queue q
which is utilized to print the queue.
Line 8: We enqueue the first binary number.
Lines 10–19: We implement a loop which dequeues an item from the queue, prints it, and appends '0'
and '1'
to it respectively.
Lines 21–22: We implement the main
function which calls the print_binary
function.
Note: You can modify the number passed to
print_binary
on line 22 to observe how the printed binary numbers change.
Queues, adhering to the FIFO principle, are versatile data structures. The code example of printing binary numbers highlights how queues can be applied to generate sequences, emphasizing their importance in programming and algorithms.
Free Resources