Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wpjerrykwok/65d18b009cd86a78a09a31455b4b07b2 to your computer and use it in GitHub Desktop.
Save wpjerrykwok/65d18b009cd86a78a09a31455b4b07b2 to your computer and use it in GitHub Desktop.
HackerRank - Algorithms - The Time in Words
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'timeInWords' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER h
# 2. INTEGER m
#
def timeInWords(h, m):
# Write your code here
# set up to convert number to words
num_in_words = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'quarter',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'half'
}
# start with empty string
words = ''
# handling those with minutes
if m != 0:
link = ' past '
# handling those after 30 min
if m > 30:
link = ' to '
m = 60 - m
if h < 12:
h += 1
else:
h = 1
if m > 20 and m < 30:
words += num_in_words[20] + ' '
m = m - 20
words += num_in_words[m]
if m > 0 and m < 30 and m != 15 and m != 30:
words += ' minute'
if m != 1:
words += 's'
words += link + num_in_words[h]
# handle those without minutes
else:
words = num_in_words[h] + " o' clock"
return words
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
h = int(input().strip())
m = int(input().strip())
result = timeInWords(h, m)
fptr.write(result + '\n')
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment