CaseyJones - 1 year ago 63

Python Question

I'm trying to workout this problem, but I am still struggling to understand the logic to solve this problem.

`hour degree = 360 / 12 = 30`

minutes degree = 360 / 12 / 60 = 0.5

So, according to this, I thought I could formulate the following function in python:

`def clockangles(hour, min):`

return (hour * 30) + (min * 0.5)

For the hour, it works fine, as it appears to have a 1=1 mapping. But for the minute there is one problem at least. When it's 0 minutes, the minutes hand points to 12.

For example:

7pm: hands pointing to 7pm and minutes pointing to 12

How do I calculate the minutes properly? Please help me understand the formula.

Answer

Okay. You are trying to find the angle between the two hands. Then this:

```
minutes degree = 360 / 12 / 60 = 0.5
```

Is just the number of degrees the *hour* hand moves per minute. Think about it - the minute hand travels a full 360 each hour. Therefore there are only 60 minutes in a full revolution. 360/60 = 6 degrees per minute for the minute hand.

So, you need to find the difference between the hour and the minute hand. Thus the function now looks like:

```
def clockangles(hour, minute):
return (hour * 30 + minute * 0.5) - (minute * 6)
```

Now, this is valid, so we could stop here. However I should explain that this can give both answers larger than 180 degrees and negative angles. If you don't want those things (and from your comments it appears that you don't), correct for them.

```
def clockangles(hour, minute):
return abs((hour * 30 + minute * 0.5) - (minute * 6))
```

Now, no negative angles.

```
def clockangles(hour, minute):
ans = abs((hour * 30 + minute * 0.5) - (minute * 6))
return min(360-ans,ans)
```

Now, the shorter of the two angles formed by measuring clockwise and counterclockwise.

Source (Stackoverflow)