0
2

More than 1 year has passed since last update.

【求対案】Python3 で時計算をやってみる

Last updated at Posted at 2022-11-12

非情報学科生向けのプログラミング講義で、以下のような問題が出題されました。

時刻を入力したら、時計の短針と長針のなす角の角度aを求めるプログラムを作成しなさい。
(0°≦a≦180°)
また、入力される時(h)と分(m)は以下の条件を満たす整数であるとする。
0≦h<12, 0≦m≦59

正時(m=0)の場合

60分進むごとに、短針は30度進むこと、6時丁度のとき180°になることを考慮して、以下のような愚直解を考えた。

#h = 8, m = 0
def solution(h, m):
    if m == 0:
        if 6 > h:
            a = 30 * h
        elif h == 6:
            a = 180
        elif h > 6:
            a = 360 - (h*30)
    return a
#120

すべての場合

しかし、以上のような解では、正時以外の場合対応できない。幸い、時と分は整数のみであるから、1.5分のような場合は考慮しなくて良い。

長針は1分毎に6°進み、短針は0.5°進むから、求めるなす角aはこれらの差であることがわかる。

#h = 5, m = 10
def solution(h, m):
    plane_time = h * 60 + m #単位変換
    long_hand = m * 6
    short_hand = plane_time * 0.5

    if abs(long_hand - short_hand) > 180:
        a = 360 - abs(long_hand - short_hand)
    else:
        a = abs(long_hand - short_hand)
    return a
#95.0

愚直な解であることは間違いないので、随時皆様のアドバイスをお待ちしております。

0
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2