Reputation: 71
I came across this problem statement in 'Think Python' book by Allan Downey:
Write a boolean function called is_after that takes two Time objects,
t1
andt2
, and returns True ift1
followst2
chronologically and False otherwise. Challenge: don't use anif
statement.
I wrote this code which seems to work fine:
class Time:
def __init__(self , hour , min , sec):
self.hour = hour
self.min = min
self.sec = sec
def is_after(t1 , t2):
if t1.hour > t2.hour:
return True
elif t1.hour == t2.hour:
if t1.min > t2.min:
return True
elif t1.min == t2.min:
if t1.sec > t2.sec:
return True
else:
return False
else:
return False
else:
return False
But the author challenges the reader to accomplish the comparison without using a conditional operator. I can't imagine how can a comparison even be done without using if/else
statements.
Upvotes: 0
Views: 547
Reputation: 17166
Taking advantage of how tuple compare works, the following would be equivalent to your posted code.
def is_after(t1, t2):
return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)
Upvotes: 3
Reputation: 395
You can calculate the total seconds of the time, and return if t1 > t2
def is_after(t1, t2):
t1_sec = 3600 * t1.hour + 60 * t1.min + t1.sec
t2_sec = 3600 * t2.hour + 60 * t2.min + t2.sec
return t1_sec > t2_sec
Upvotes: 4