asp提高网站安全性的措施,wordpress客户端连接,包头网站建设 奥北,jquery效果网站CheckiO 是面向初学者和高级程序员的编码游戏#xff0c;使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务#xff0c;从而提高你的编码技能#xff0c;本博客主要记录自己用 Python 在闯关时的做题思路和实现代码#xff0c;同时也学习学习其他大神写的代码。
Chec…
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 题目描述
【Time Converter (24h to 12h)】你更喜欢旧的12小时制。但是我们生活的现代世界宁愿使用24小时制你可以在任何地方看到它。您的任务是按照以下规则将时间从24小时格式转换为12小时格式输出格式应为“hh:mm a.m.”中午前数小时或“hh:mm p.m.”中午后数小时如果小时少于10小时不要在之前写 “0”。例如“9:05 am”
【链接】https://py.checkio.org/mission/time-converter-24h-to-12h/
【输入】24小时格式的时间字符串类型
【输出】12小时格式的时间字符串类型
【前提】‘00:00’ time ‘23:59’
【范例】
time_converter(12:30) 12:30 p.m.
time_converter(09:00) 9:00 a.m.
time_converter(23:15) 11:15 p.m.解题思路
使用 time.strptime() 方法把原始的时间字符串按照 %H:%M24小时制小时:分钟数的格式解析为时间元组
使用 time.strftime() 方法接收时间元组按照 %I:%M %p12小时制小时:分钟数 本地AM或PM的等价符的格式转换为可读字符串
经过以上两个步骤后12:30 就会变成 12:30 PM由于题目要求变成 12:30 p.m.所以可以利用 split() 方法对字符串进行分割将 PM 替换成 p.m.AM 替换成 a.m.
因为题目要求10点以前的比如 09:00 要去掉前面的0变成 9:00 a.m.所以可以先将前面替换后的列表转换成字符串再利用 list() 方法将字符串每一个字符作为一个元素转换成列表此时如果列表第一个元素为0就将其替换掉就行了
代码实现
import timedef time_converter(init_time):init_time time.strptime(init_time, %H:%M)init_time time.strftime(%I:%M %p, init_time)init_time init_time.split( )if init_time[1] PM:init_time[1] p.m.else:init_time[1] a.m.init_time .join(init_time)init_time list(init_time)if init_time[0] 0:init_time[0] init_time .join(init_time)return init_timeif __name__ __main__:print(Example:)print(time_converter(12:30))# These asserts using only for self-checking and not necessary for auto-testingassert time_converter(12:30) 12:30 p.m.assert time_converter(09:00) 9:00 a.m.assert time_converter(23:15) 11:15 p.m.print(Coding complete? Click Check to earn cool rewards!)大神解答 大神解答 NO.1 def time_converter(time):h, m map(int, time.split(:))return f{(h-1)%121}:{m:02d} {ap[h11]}.m.以 13:30 为例首先将时间字符串进行分割
h 13、m 30
(h-1)%121 (13-1)%121 1
这个 m:02d 可能比较难理解这里表示指定了 m 的输出格式02d 相当于 print 中的 02d%02d% 表示输出的数是两位数不够两位数则补0举例
a 3
b 30
print(%02d %a)
print(%02d %b)
print(%03d %a)
print(%03d %b)输出结果依次为
03
30
003
030后面一个表达式也是令人吃惊ap[h11] h11 返回的结果为 True 或者 False然后根据此结果来获取字符串 ap 的第0个或第1个元素不愧是大神的代码学到了 大神解答 NO.2 def time_converter(time):h, m map(int, time.split(:))if h 12:ampm a.m.else:ampm p.m.if h 12:h - 12elif h 0:h 12return %d:%02d %s % (h, m, ampm)大神解答 NO.3 def time_converter(str_time):hours, minutes map(int, str_time.split(:))am_or_pm [a.m., p.m.][hours 12]return f{(hours-1) % 121}:{minutes:02} {am_or_pm}