Angle Between Time

Given a time, your mission is to calculate the angle between the hour hand and the minute hand on an analog clock and return it in radians. The returned value should be written as a reduced fraction or, if the fraction's denominator is 1, as a regular number. There should be no multiplication sign in front of pi.

The Idea: Begin with building a few conversions. We know that 360 degrees fits into 12 hours, so 30*hr = 1hr. Next, 360 degrees fits 60 minutes, so 1min = 6*min. There is more more detail. The current minute hand effects the angle of the hour hand. That is, 60 mins = 30 degrees, so 1 minute adds an addition .5 degrees to the hour hand, 1*min =.5. Using this, we can convert from hours or degrees to minutes, convert to radians, and finally convert it into a fraction.

Complexity: Constant time and space

from fractions import Fraction

def angle_time(time):
    hr, min = time.split(':')
    hr_angle = 30*int(hr) + .5*int(min)
    min_angle =6*int(min)
    angle = abs(hr_angle - min_angle)
    fraction = Fraction(int(angle), 180)

    # pretty print
    if fraction.denominator == 1:
        return str(fraction.numerator) + 'pi'
    return str(fraction.numerator) + 'pi' + '/' + str(fraction.denominator)

print(angle_time('10:20'))

Last updated