PROBLEM UNDERSTANDING SOLUTION - Working with Dates and Times in Python Practice Problems #13

Hello there!
I´m trying to understand how the solution of this exercise works, especially the Event class.

The goal of this problem is to count what is the maximum number of sessions that where ongoing on at any given time. Two sessions will be ongoing at the same time if there is at least one moment other than the start and end times where the two sessions coincide.

Above it´s a screenshot of how the csv is structured.
Here´s the code for the solution:

import datetime as dt

# Write your solution below
class Event():
    
    def __init__(self, time, is_start):
        self.time = time
        self.is_start = is_start
    
    def __lt__(self, other):
        """
        Function used to sort the events
        """
        if self.time == other.time:
            return self.is_start
        return self.time < other.time

# Read the CSV file
import csv
f = open('session_log.csv')
reader = csv.reader(f)
rows = list(reader)[1:]

# Create all events
events = []
for row in rows:
    row = [int(x) for x in row]
    session_start = dt.datetime(row[1], row[2], row[3], row[4], row[5])
    session_end = dt.datetime(row[6], row[7], row[8], row[9], row[10])
    start_event = Event(session_start, True)
    end_event = Event(session_end, False)
    events.append(start_event)
    events.append(end_event)

# Sort the events by time, break ties by putting end events first
events.sort()

# Calculate the maximum number of simultaneous sessions
session_count = 0
max_sessions = None
for event in events:
    if event.is_start:
        session_count += 1
    else:
        session_count -= 1
    if max_sessions == None or session_count > max_sessions:
        max_sessions = session_count

print(max_sessions)

I understand the whole logic of the solution, but I still don´t understand what happens inside the Event class especially in the lt function.
Can anyone please give me a hand?
Thanks in advance!

Normally we can’t use multiple constructors in case of python OOP.

class Event():
    
    def __init__(self, time, is_start):
        self.time = time
        self.is_start = is_start
    
    def __lt__(self, other):
        """
        Function used to sort the events
        """
        if self.time == other.time:
            return self.is_start
        return self.time < other.time

I’ts a bypass way to define multiple constructor in python Class.
__lt__() helps you to determine this statements.
start_event = Event(session_start, True)
end_event = Event(session_end, False)
You can check out this link:

1 Like