Hackbright Code Challenges

Time Word: Solution

Time Word: Solution

Problem

Time Word

Challenge

Medium

Concepts

General

Download

timeword-solution.zip


First, we define some useful constants:


HOURS = ["twelve", "one", "two", "three", "four", "five", "six",
         "seven", "eight", "nine", "ten", "eleven"]

ONES = ["", "one", "two", "three", "four", "five", "six",
        "seven", "eight", "nine", "ten", "eleven", "twelve",
        "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
        "eighteen", "nineteen"]

TENS = ["", "", "twenty", "thirty", "forty", "fifty"]

Then, our function:

def time_word(time):
    """Convert time to text."""

    # START SOLUTION

    if time == "00:00":
        return "midnight"

    if time == "12:00":
        return "noon"

    # "06:30" -> 6 hours, 30 minutes
    hours, minutes = time.split(":")
    hours = int(hours)
    minutes = int(minutes)

    # Add hour (uses 'twelve' for 0)
    out = HOURS[hours % 12] + " "

    if minutes >= 20:  # "twenty " ... "fifty nine"
        out += TENS[minutes // 10] + " " + ONES[minutes % 10]

    elif minutes >= 10:  # "ten", "eleven", ..., "nineteen"
        out += ONES[minutes]

    elif minutes > 0:  # "oh one" ... "oh nine"
        out += "oh " + ONES[minutes]

    else:
        out += "o'clock"

    # There might be space at the end (if we ended with a tens
    # and nothing after it, like 06:30 -> "six thirty "), so
    # strip it off, then add a space and am/pm indicator.
    return out.rstrip() + (" pm" if hours >= 12 else " am")