Skip to content

Instantly share code, notes, and snippets.

@8enmann
Created June 21, 2019 02:05
Show Gist options
  • Save 8enmann/5eab7f26fdf36d6f1cefafdd51b0b706 to your computer and use it in GitHub Desktop.
Save 8enmann/5eab7f26fdf36d6f1cefafdd51b0b706 to your computer and use it in GitHub Desktop.
Format time in Python using pytest
"""
TDD solution to:
Input: a bunch of times, minutes and seconds, formatted as a single string like: "12:32 34:01 15:23 9:27 55:22 25:56"
Output: the sum of the times, hours, minutes, and seconds, formatted as a single string like: "2:32:41"
https://github.com/cjdev/interview-preparation
https://coderpad.io/sandbox
"""
import pytest
def sum_times(input_str: str) -> str:
"""Sums the space separated times in the input and formats as a string.
Args:
input_str: a bunch of times, minutes and seconds, formatted as a single string like: "12:32 34:01 15:23 9:27 55:22 25:56"
Returns:
The sum of the times, hours, minutes, and seconds, formatted as a single string like: "2:32:41"
"""
if not input_str:
return '0:00:00'
times = input_str.split(' ')
tuples = [time.split(":") for time in times]
sums = [sum(int(x[t]) for x in tuples) for t in range(2)]
minutes, seconds = divmod(sums[1], 60)
minutes += sums[0]
hours, minutes = divmod(minutes, 60)
return f'{hours}:{minutes:2d}:{seconds:02d}'
def test_example():
assert sum_times("12:32 34:01 15:23 9:27 55:22 25:56") == "2:32:41"
def test_empty():
assert sum_times("") == '0:00:00'
def test_short():
assert sum_times("12:32") == "0:12:32"
def test_zero():
assert sum_times("12:02") == "0:12:02"
pytest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment