สมมติว่ามีอินพุต hour และ minutes ต้องแสดงเวลาเป็นข้อความ เช่น:
8:00→eight o' clock8:01→one minute past eight8:10→ten minutes past eight8:15→quarter past eight8:30→half past eight8:40→twenty minutes to nine8:45→quarter to nine8:47→thirteen minutes to nine
ตัวอย่าง: h = 9, m = 42 ผลลัพธ์ eighteen minutes to ten
วิธีแก้ปัญหา
- สร้างลิสต์
textสำหรับตัวเลข 1-30 รวมคำพิเศษquarter,half - ตรวจสอบเงื่อนไขของ
m:m == 0:text[h-1] + " o' clock"m == 1:text[0] + " minute past " + text[h-1]m == 15:text[14] + " past " + text[h-1]m == 30:text[29] + " past " + text[h-1]m < 30:text[m-1] + " minutes past " + text[h-1]m == 45:"quarter to " + text[h]- อื่นๆ:
text[60-m-1] + " minutes to " + text[h]
ตัวอย่างโค้ด
def solve(h, m):
text = ["one","two","three","four","five","six","seven","eight",
"nine","ten","eleven","twelve","thirteen","fourteen","quarter",
"sixteen","seventeen","eighteen","nineteen","twenty",
"twenty-one","twenty-two","twenty-three","twenty-four",
"twenty-five","twenty-six","twenty-seven","twenty-eight",
"twenty-nine","half"]
if m == 0:
return text[h-1] + " o' clock"
elif m == 1:
return text[0] + " minute past " + text[h-1]
elif m == 15:
return text[14] + " past " + text[h-1]
elif m < 30:
return text[m-1] + " minutes past " + text[h-1]
elif m == 30:
return text[29] + " past " + text[h-1]
elif m == 45:
return "quarter to " + text[h]
else:
return text[60-m-1] + " minutes to " + text[h]
h = 9
m = 42
print(solve(h, m))
อินพุต
9, 42
เอาต์พุต
eighteen minutes to ten