I'm trying to write a boolean function that takes two Mytime objects, t1 and t2 as arguments, and returns True if the object falls inbetween the two times.

This is a question from the How to Think Like a Computer Scientist book, and I need help.

What I've gotten so far:

``````class MyTime:
def __init__(self, hrs=0, mins=0, secs=0):
self.hours = hrs
self.minutes = mins
self.seconds = secs

def between(t1, t2):
if t1 <= t2:
return True
else:
return False
``````

I just don't understand how to make a function that uses MyTime objects into the boolean function? Any help would be great.

You might try something like this ...

``````# compareTimes.py #

class MyTime: # 24 hour clock #

def __init__(self, hrs=0, mins=0, secs=0):
self.hours = hrs
self.minutes = mins
self.seconds = secs
# normalize ... #
if self.seconds >= 60:
self.minutes += self.seconds//60
self.seconds = self.seconds % 60
if self.minutes >= 60:
self.hours += self.minutes//60
self.minutes = self.minutes % 60
if self.hours >= 24:
self.hours = self.hours % 24

def get_sec(self):
return (self.hours*60 + self.minutes) * 60 + self.seconds

def __str__(self):
return '{:02d}:{:02d}:{:02d}'.\
format( self.hours, self.minutes, self.seconds )

def between( t1, t, t2 ):
return t1.get_sec() <= t.get_sec() <= t2.get_sec()

t1 = MyTime( 9, 59, 59 )
print( 't1 =', t1 )

t2 = MyTime( 10, 0, 1 )
print( 't2 =', t2 )

t = MyTime( 10, 0, 0 )
print( 't =', t )

print( 'between( t2, t, t1 ) =', between( t2, t, t1 ) )
print( 'between( t1, t, t2 ) =', between( t1, t, t2 ) )
print( 'between( t, t1, t2 ) =', between( t, t1, t2 ) )

print( 'between( t, t, t ) =', between( t, t, t ) )
``````

Just wondering, but shouldn't it be returning True when its between(t1, t, t2)? It currently returns False.

Yes ... it is.

These are the program output results I get:

t1 = 09:59:59
t2 = 10:00:01
t = 10:00:00
between( t2, t, t1 ) = False
between( t1, t, t2 ) = True # NOTE: True as expected #
between( t, t1, t2 ) = False
between( t, t, t ) = True

Actually ... the notion of 'between' ...

could actually be expressed as this:

``````class MyTime: # 24 hour clock #

def __init__(self, hrs=0, mins=0, secs=0):
self.hours = hrs
self.minutes = mins
self.seconds = secs
# normalize ... #
if self.seconds >= 60:
self.minutes += self.seconds//60
self.seconds = self.seconds % 60
if self.minutes >= 60:
self.hours += self.minutes//60
self.minutes = self.minutes % 60
if self.hours >= 24:
self.hours = self.hours % 24

def get_sec(self):
return (self.hours*60 + self.minutes) * 60 + self.seconds

def __str__(self):
return '{:02d}:{:02d}:{:02d}'.\
format( self.hours, self.minutes, self.seconds )

def between(self, t1, t2 ):
return t1.get_sec() <= self.get_sec() <= t2.get_sec() \
or t2.get_sec() <= self.get_sec() <= t1.get_sec()
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.