classDateRange:
def__init__(self, start, end):
self.start = start
self.end = end
def__contains__(self, date):
return self.start <= date <= self.end
def__repr__(self):
returnf"DateRange({self.start}, {self.end})"from datetime import date
q1 = DateRange(date(2024, 1, 1), date(2024, 3, 31))
print(f"Feb 15 in Q1: {date(2024, 2, 15) in q1}")
print(f"Apr 15 in Q1: {date(2024, 4, 15) in q1}")
# Without __contains__, Python falls back to __iter__classOdds:
def__iter__(self):
n = 1while n < 20:
yield n
n += 2
odds = Odds()
print(f"7 in odds: {7 in odds}")
print(f"8 in odds: {8 in odds}")
Output
Click "Run" to execute your code
Implement __contains__ for O(1) membership testing. Without it, Python falls back to iterating through __iter__, which is O(n).
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?