Hackerrank - The Time in Words Solution
1 min read

Hackerrank - The Time in Words Solution

Hackerrank - The Time in Words Solution

Given the time in numerals we may convert it into words, as shown below:

At , use o' clock. For , use past, and for  use to. Note the space between the apostrophe and clock in o' clock. Write a program which prints the time in words for the input given in the format described.

Function Description

Complete the timeInWords function in the editor below. It should return a time string as described.

timeInWords has the following parameter(s):

  • h: an integer representing hour of the day
  • m: an integer representing minutes after the hour

Input Format

The first line contains , the hours portion The second line contains , the minutes portion


Output Format

Print the time in words as described.

Sample Input 0


Sample Output 0

thirteen minutes to six

Sample Input 1


Sample Output 1

three o' clock

Sample Input 2


Sample Output 2

quarter past seven

Solution in Python

def timeInWords(h, m):
    n = [
        "twenty one",
        "twenty two",
        "twenty three",
        "twenty four",
        "twenty five",
        "twenty six",
        "twenty seven",
        "twenty eight",
        "twenty nine",
    m = int(m)
    h = int(h)
    if not m:
        return "%s o' clock" % n[h]
    if m>30: 
        m = 60 - m
        w = "to"
        h = (h+1)%12 or 12
        w = "past"
    o = " minutes"
    if m==1:
        o = " minute"
    elif not m%15:
        o = ""
    m = n[m]
    h = n[h]
    return "%s%s %s %s"%(m,o,w,h)

print(timeInWords(input(), input()))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.