물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Human readable duration format

BEstyle 2022. 10. 26. 13:09

DESCRIPTION:

Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.

The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.

It is much easier to understand with an example:

* For seconds = 62, your function should return 
    "1 minute and 2 seconds"
* For seconds = 3662, your function should return
    "1 hour, 1 minute and 2 seconds"

For the purpose of this Kata, a year is 365 days and a day is 24 hours.

Note that spaces are important.

Detailed rules

The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.

Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.

A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.

A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.


 

def format_duration(s):
    if s==0:
        return "now"
    print(s)
    asec=1
    amin=asec*60
    ahour=amin*60
    aday=ahour*24
    ayear=aday*365
    year=s//ayear
    day=(s%ayear)//aday
    hour=((s%ayear)%aday)//ahour
    min=(((s%ayear)%aday)%ahour)//amin
    sec=(((s%ayear)%aday)%ahour)%amin
    alist=[singular(year,"year"),singular(day,"day"),singular(hour,"hour"),singular(min,"minute"),singular(sec,"second")]
    blist=[]
    for i in alist:
        if i!=None:
            blist.append(i)
    if len(blist)==1:
        return blist[0]
    ans=", ".join(blist[:-1])
    ans+=" and " +blist[-1]
    return ans
    
    
    
def singular(num, measure):
    if num==0:
        return
    elif num==1:
        return str(num)+" "+measure
    elif num>=2:
        return str(num)+" "+measure+"s"

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Converting string to camel case  (0) 2022.10.26
Counting Duplicates  (0) 2022.10.26
New Cashier Does Not Know About Space or Shift  (0) 2022.10.25
Decipher this!  (0) 2022.10.25
Matrix Addition  (0) 2022.10.24