Design a function that calculates the angle between the hour and minute hands on a clock, given the hour and minute.
This problem requires calculating the angle between the hour and minute hands on a clock, given the hour and minute. Here's a function to do that, along with explanations and analysis.
def angle_between_hands(hour, minute):
"""Calculates the angle between the hour and minute hands on a clock.
Args:
hour (int): The hour (0-11).
minute (int): The minute (0-59).
Returns:
float: The angle between the hour and minute hands in degrees.
"""
# Validate inputs
if not (0 <= hour <= 11 and 0 <= minute <= 59):
raise ValueError("Invalid hour or minute value")
# Calculate the position of the hour hand
hour_angle = (hour % 12 + minute / 60) * 30 # 30 degrees per hour
# Calculate the position of the minute hand
minute_angle = minute * 6 # 6 degrees per minute
# Calculate the difference between the two angles
angle = abs(hour_angle - minute_angle)
# Return the smaller angle (angle <= 180)
return min(360 - angle, angle)
# Example usage
hour = 3
minute = 30
angle = angle_between_hands(hour, minute)
print(f"The angle between the hour and minute hands at {hour}:{minute} is {angle} degrees.")
hour = 6
minute = 0
angle = angle_between_hands(hour, minute)
print(f"The angle between the hour and minute hands at {hour}:{minute} is {angle} degrees.")
hour = 12
minute = 0
angle = angle_between_hands(hour, minute)
print(f"The angle between the hour and minute hands at {hour}:{minute} is {angle} degrees.
")
The function angle_between_hands
calculates the angle between the hour and minute hands as follows:
ValueError
.(hour % 12 + minute / 60) * 30
.minute * 6
.The run-time complexity of this function is O(1) because it involves only a fixed number of arithmetic operations, regardless of the input values. There are no loops or recursive calls. The calculations performed are basic arithmetic operations (addition, multiplication, division), and comparisons, all of which take constant time.
The space complexity of this function is also O(1). It only uses a fixed number of variables to store the hour, minute, and calculated angles. The amount of memory used does not depend on the input values. The function uses only primitive data types (integers and floats), which require a constant amount of space.
ValueError
if the input is invalid.hour % 12
handles this case correctly because 12 % 12
is 0.