본문 바로가기
프로그래밍 문제/[Python] CheckIO

[Check-IO] Time converter

by UltraLowTemp-Physics 2021. 12. 10.
728x90

1. Problem: https://py.checkio.org/en/mission/time-converter-24h-to-12h/

2. My solutions 

def time_converter(time):
    #replace this for solution
    hour, minutes = time.split(":")
    hour = int(hour)
    if hour > 12 or  hour == 12:
        if hour > 12: hour = hour - 12
        day_night = 'p.m.'
    else:
        if hour == 0: hour = 12 
        day_night = 'a.m.' 
        
    time_string = "%d:%s %s" %(hour, minutes, day_night)    
    
    return time_string

if __name__ == '__main__':
    print("Example:")
    print(time_converter('12:30'))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert 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!")

 

[3] Best Solutions

def time_converter(time):
    h, m = map(int, time.split(':'))
    return f"{(h-1)%12+1}:{m:02d} {'ap'[h>11]}.m."

(1) h와 m을 int로 얻음 
(2) {m:02d} 
   - 변수 m
   - 02: 몇 개의 숫자가 포함이 될 것인지 
   - d : decimal 
(3) 'ap'[h>11] 
    - [h>11] : resolve to True or False --> True and False are corresponding to 1 and 0 numerically
    - Therefore, if h > 12, that is true, 'ap'[1] -> 'p' while if h < 12, 'ap'[0] -> 'a' 

728x90

'프로그래밍 문제 > [Python] CheckIO' 카테고리의 다른 글

[Check-IO] Common Words  (0) 2021.12.16
[Check-IO] Sum by Type  (0) 2021.12.12
[CheckIO] Goes Right After  (0) 2021.12.03
[Check-IO] Absolute Sorting  (0) 2021.11.14
[Check-IO] Frequency Sorting  (0) 2021.04.18

댓글