Introduction to Practice Problems

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.

First Practice Problem: Implementing Queues with Deques

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.

from collections import deque

class Queue:
    def __init__(self):
        # Initializing an empty queue
        self.buffer = deque()

    def enqueue(self, val):
        # Adding (enqueueing) an item to the queue
        self.buffer.appendleft(val)

    def dequeue(self):
        # Removing (dequeuing) an item from the queue
        return self.buffer.pop()

    # Checking if the queue is empty
    def is_empty(self):
        return len(self.buffer)==0

    # Checking the size (number of items) in the queue
    def size(self):
        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.

Analyzing the First Problem Solution

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.

Second Practice Problem: Using Sorted Maps with Custom Class as a Key

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.

class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    # Defining comparator for custom class
    def __lt__(self, other):
        if self.score == other.score:
            return self.name < other.name
        return self.score < other.score
    
    def __gt__(self, other):
        if self.score == other.score:
            return self.name > other.name
        return self.score > other.score
    
    def __eq__(self, other):
        return self.score == other.score and self.name == other.name

    def __hash__(self):
        return hash((self.name, self.score))
     
    # Defining the string representation of Player object
    def __repr__(self):
        return str((self.name, self.score))


from sortedcontainers import SortedDict

# Create a sorted map
scores = SortedDict()

player1 = Player("John", 900)
player2 = Player("Doe", 1000)

# Adding players to the SortedDict
scores[player1] = player1.score
scores[player2] = player2.score

# Print SortedDict
for player, score in scores.items():
    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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal