Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # talking_clock.py
- from sys import argv
- def read_input(filepath='input.txt'):
- with open(filepath, 'r') as f:
- return [l.strip() for l in f.readlines()]
- def num_to_words(num):
- num = int(num)
- if num > 60:
- raise NotImplementedError('num_to_words is not implemented for non-time numbers')
- lows = {0: 'oh', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven',
- 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve'}
- highs = {2: 'twenty', 3: 'thirty', 4: 'fourty', 5: 'fifty', 6: 'sixty'}
- result = ''
- if num <= 12:
- result = lows[num]
- elif num <= 19:
- prefix = lows[num % 10] if num != 15 else 'fif'
- result = '{}teen'.format(prefix)
- else:
- result = highs[num // 10]
- low = num % 10
- if low != 0:
- result += ' {}'.format(lows[low])
- return result
- def hour_to_words(hour_string):
- hour = int(hour_string)
- pm = hour >= 12
- if pm and hour != 12:
- hour = hour - 12
- elif not pm and hour == 0:
- hour = 12
- am_or_pm = 'pm' if pm else 'am'
- return (num_to_words(hour), am_or_pm)
- def minutes_to_words(minutes_string):
- minutes = int(minutes_string)
- result = ''
- if minutes > 0:
- oh = 'oh ' if minutes < 10 else ''
- result = '{}{}'.format(oh, num_to_words(minutes))
- return result
- def time_to_words(time_string):
- hours, minutes = time_string.strip().split(':')
- hour_string, am_or_pm = hour_to_words(hours)
- minutes_string = minutes_to_words(minutes)
- return ' '.join([hour_string, minutes_string, am_or_pm]).replace(' ', ' ')
- if __name__ == '__main__':
- input_time = []
- if len(argv) > 1:
- input_time = read_input(filepath=argv[1])
- else:
- input_time.extend(read_input())
- for t in input_time:
- print('It\'s {}'.format(time_to_words(t)))
- # ------------------------------------
- # test file
- # test_talking_clock.py
- import pytest
- import talking_clock as T
- def test_num_to_words():
- assert T.num_to_words('1') == 'one'
- assert T.num_to_words('11') == 'eleven'
- assert T.num_to_words('15') == 'fifteen'
- assert T.num_to_words('44') == 'fourty four'
- assert T.num_to_words('60') == 'sixty'
- with pytest.raises(NotImplementedError):
- T.num_to_words('69')
- def test_time_to_words():
- assert T.time_to_words('11:11') == 'eleven eleven am'
- assert T.time_to_words('12:59') == 'twelve fifty nine pm'
- assert T.time_to_words('13:09') == 'one oh nine pm'
- assert T.time_to_words('00:00') == 'twelve am'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement