Welcome to the practical segment of our Python programming journey! Today, we're applying the knowledge from past lessons to solve two practice problems using advanced Python data structures: queues
, deques
, and sorted maps
with custom class keys
.
Consider an event-driven system, like a restaurant. Orders arrive, and they must be handled in the order they were received, following the First In, First Out (FIFO) principle. This principle makes it a perfect scenario for a queue
or deque
implementation in Python.
Python1from collections import deque 2 3class Queue: 4 def __init__(self): 5 # Initializing an empty queue 6 self.buffer = deque() 7 8 def enqueue(self, val): 9 # Adding (enqueueing) an item to the queue 10 self.buffer.appendleft(val) 11 12 def dequeue(self): 13 # Removing (dequeuing) an item from the queue 14 return self.buffer.pop() 15 16 # Checking if the queue is empty 17 def is_empty(self): 18 return len(self.buffer)==0 19 20 # Checking the size (number of items) in the queue 21 def size(self): 22 return len(self.buffer)
This code demonstrates the creation and operation of a Queue
class, which leverages collections.deque
to efficiently implement a queue. The Queue
class includes methods to enqueue
(add) an item, dequeue
(remove) an item, check if the queue is empty, and return the queue's size. Enqueue operations add an item to the left end of the deque (simulating the arrival of a new order), while dequeue operations remove an item from the right end (simulating the serving of an order), maintaining the First In, First Out (FIFO) principle.
We've mimicked a real-world system by implementing a queue
using Python's deque
. The enqueuing of an item taps into the LIFO principle, similar to the action of receiving a new order at the restaurant. The dequeuing serves an order, reflecting the preparation and delivery of the order.
For the second problem, envision a leaderboard for a video game. Players with their scores can be represented as objects of a custom class
, then stored in a sorted map
for easy and efficient access.
This code creates a Player
custom class and uses it as keys in a SortedDict
, a sorted map object from the sortedcontainers
library.
Python1class Player: 2 def __init__(self, name, score): 3 self.name = name 4 self.score = score 5 6 # Defining comparator for custom class 7 def __lt__(self, other): 8 if self.score == other.score: 9 return self.name < other.name 10 return self.score < other.score 11 12 def __gt__(self, other): 13 if self.score == other.score: 14 return self.name > other.name 15 return self.score > other.score 16 17 def __eq__(self, other): 18 return self.score == other.score and self.name == other.name 19 20 def __hash__(self): 21 return hash((self.name, self.score)) 22 23 # Defining the string representation of Player object 24 def __repr__(self): 25 return str((self.name, self.score)) 26 27 28from sortedcontainers import SortedDict 29 30# Create a sorted map 31scores = SortedDict() 32 33player1 = Player("John", 900) 34player2 = Player("Doe", 1000) 35 36# Adding players to the SortedDict 37scores[player1] = player1.score 38scores[player2] = player2.score 39 40# Print SortedDict 41for player, score in scores.items(): 42 print(player) # e.g., ('John', 900)
This code snippet introduces a Player
class for representing players in a video game, incorporating custom comparison operators to allow sorting by score (primary) and name (secondary). Instances of this class are then used as keys in a SortedDict
from the sortedcontainers
library, ensuring that players are stored in a manner that is sorted first by their scores and then by their names if scores are equal. This is essential for functionalities like leaderboards, where players need to be ranked efficiently according to their performance.
In our leaderboard system, we used a Player
custom class with comparator methods for sorting. We stored instances of Player
in a sorted map with their corresponding scores. The SortedDict
allows us to access player scores in a sorted order efficiently, a common requirement in a competitive gaming system.
By practicing with these real-world examples, you'll solidify your understanding of these fundamental techniques and prepare for more advanced exercises.
We've successfully employed Python's built-in data structures — queues
or deques
, and sorted maps
— to solve real-world problems. This hands-on approach enables us to better understand these concepts. More exercises to cement your understanding are coming up next. Happy coding!