309. Python Program to Find the Angle Between Clock Hands
HardPhase 3 · Challenge
This one takes a few steps, but you know every tool it uses: split(), % and if. Draw a clock at 3:30 on paper first and look closely at where the hour hand is.
Overview
This is a common interview question. It looks easy, but it hides a trap: the hour hand does not jump from one hour to the next, it moves a little every minute.
Problem Statement
Pablo draws a clock for a phone app. To draw the hands, Pablo needs the angle between them at any time. Read a time and print the smaller angle between the hour hand and the minute hand, in degrees. Use these facts:
- A full turn of the clock is 360 degrees, and angles are measured from 12 o'clock, going clockwise.
- The minute hand moves 6 degrees each minute, because 360 / 60 is 6.
- The hour hand moves 30 degrees each hour, because 360 / 12 is 30. It also moves 0.5 degrees each minute, because 30 / 60 is 0.5.
- The two hands make two angles that add up to 360. Print the smaller one, so the answer is from 0 to 180.
The clock face shows only 12 hours, so 15:30 looks the same as 03:30. Print the angle with 1 decimal place, like 75.0, and nothing else.
Examples
Example 1. Input 03:30 gives:
75.0
Why: the minute hand is at 30 times 6 = 180 degrees. The hour hand is at 3 times 30 = 90, plus 30 times 0.5 = 15, so 105 degrees. The difference is 75.
Example 2. Input 09:00 gives:
90.0
Why: the hour hand is at 9 times 30 = 270 degrees and the minute hand is at 0. The difference is 270, so the smaller angle is 360 - 270 = 90.
Input
One line: a time in the 24-hour format HH:MM, from 00:00 to 23:59. The hours and the minutes always have 2 digits. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One number with 1 decimal place, from 0.0 to 180.0. The tests try 10 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.