【Python CheckiO 题解】Sun Angle
CheckiO 是面向初學者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰和有趣的任務,從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關時的做題思路和實現代碼,同時也學習學習其他大神寫的代碼。
CheckiO 官網:https://checkio.org/
我的 CheckiO 主頁:https://py.checkio.org/user/TRHX/
CheckiO 題解系列專欄:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有題解源代碼:https://github.com/TRHX/Python-CheckiO-Exercise
題目描述
【Sun Angle】:您的任務是在知道一天中的時間的情況下找到太陽在地平線上方的角度。例如:太陽在 6:00 AM 在東方升起,對應于0°角。在 12:00 PM,太陽到達頂點,這意味著該角度等于90°,6:00 PM 是日落時間,因此角度為180°,如果時間是夜晚時間(上午6:00之前或下午6:00之后),則您的函數應返回“I don’t see the sun!”。
【鏈接】:https://py.checkio.org/mission/sun-angle/
【輸入】:一天中的時間
【輸出】:太陽的角度,四舍五入到小數點后兩位
【前提】:00:00 <= time <= 23:59
【范例】:
sun_angle("07:00") == 15 sun_angle("12:15"] == 93.75 sun_angle("01:23") == "I don't see the sun!"解題思路
將輸入的時間字符串進行分割,分為小時和分鐘兩部分
分析時針,06:00 對應 0°,07:00 對應 15°,18:00 對應 180°,也就是每增加 1 個小時,度數就增加 15°
分析分針,60 分鐘等于 1 小時,分針轉 1 圈(360°)時針轉 1/24 圈(15°),那么 1 分鐘,時針轉 0.25°
如果是整點,那么只需要計算有多少個 15° 就行了
如果不是整點,除了要計算有多少個 15° ,還需要計算有多少個 0.25°,最后兩者相加
注意時鐘要大于等于 6 并且小于 18,此外,還有特殊的 18 點整等于 180°
代碼實現
def sun_angle(time):time = time.split(':')if int(time[0]) == 18 and int(time[1]) == 0:return int(180)elif 6 <= int(time[0]) < 18:if int(time[1]) > 0:return (int(time[0])-6)*15 + int(time[1])*0.25else:return (int(time[0])-6)*15else:return "I don't see the sun!"if __name__ == '__main__':print("Example:")print(sun_angle("07:00"))# These "asserts" using only for self-checking and not necessary for auto-testingassert sun_angle("07:00") == 15assert sun_angle("01:23") == "I don't see the sun!"print("Coding complete? Click 'Check' to earn cool rewards!")大神解答
大神解答 NO.1
def sun_angle(time):h, m = list(map(int, time.split(':')))angle = 15 * h + m / 4 - 90return angle if 0 <= angle <= 180 else "I don't see the sun!"看了大神的代碼才知道自己寫的代碼有多菜!如此簡潔明了,完全不用我那么復雜!
大神解答 NO.2
def sun_angle(time):t = int(time[:2]) * 15 + int(time[3:]) / 4 - 90return t if 0 <= t <= 180 else "I don't see the sun!"大神解答 NO.3
from datetime import datetime from scipy.interpolate import interp1dsolutions = {'06:00': 0, '12:00': 90, '18:00': 180} stamp = lambda time: datetime.strptime(time, '%H:%M').timestamp() line = interp1d([*map(stamp, solutions)], [*solutions.values()])def sun_angle(time):try: return line(stamp(time))[()]except ValueError: return "I don't see the sun!"總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Sun Angle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新一代神U预定 曝骁龙8+下放中端降维对
- 下一篇: 5千条轨迹解开北京病例感染谜团:病例路过