Algorithm/codewars

Human readable duration format 답안

Bonita SY 2021. 4. 1. 21:01
728x90
반응형

문제)

www.codewars.com/kata/52742f58faf5485cae000b9a/train/python

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

 

내가 푼 답)

def format_duration(seconds):
    if seconds == 0:
        return "now"
    
    time = {
        "sec": seconds,
        "min": 0,
        "hour": 0,
        "day": 0,
        "year": 0
    }
    a_to_b(time, 'sec', 'min', 60)
    a_to_b(time, 'min', 'hour', 60)
    a_to_b(time, 'hour', 'day', 24)
    a_to_b(time, 'day', 'year', 365)
    
    singular = {
        'year': 'year',
        'day': 'day',
        'hour': 'hour',
        'min': 'minute',
        'sec': 'second'
    }
    plural = {
        'year': 'years',
        'day': 'days',
        'hour': 'hours',
        'min': 'minutes',
        'sec': 'seconds'
    }
    
    result = []
    for key in ['year', 'day', 'hour', 'min', 'sec']:          
        if (time[key] < 1):
            continue
            
        tmp_result = str(time[key]) + ' '
            
        if (time[key] == 1):
            tmp_result += singular[key]
        else:
            tmp_result += plural[key]
            
        result.append(tmp_result)

    return ', '.join(result[:-1]) + ' and ' + result[-1] if len(result) > 1 else result[0]
    
def a_to_b(time, a, b, criteria):
    while (time[a] >= criteria):
        time[a] -= criteria
        time[b] += 1

 

테스트 결과)

 

마음에 드는 남이 푼 답)

728x90
반응형

'Algorithm > codewars' 카테고리의 다른 글

IQ Test 답안  (0) 2021.04.01
Take a Ten Minute Walk 답안  (0) 2021.04.01
Credit Card Mask 답안  (0) 2021.04.01
Format a string of names like 'Bart, Lisa & Maggie'. 답안  (0) 2021.04.01
Catching Car Mileage Numbers 답안  (0) 2021.04.01