Last active
August 29, 2015 14:01
-
-
Save foxx/e55897f4c45081f06c06 to your computer and use it in GitHub Desktop.
Stopwatch Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A stopwatch records lap times as strings of the form "MM:SS:HS" | |
MM = minutes; SS = seconds; and HS = hundredths of a second. | |
Write a function that accepts two lap times and calculates their average, | |
returning the result in the same string format. | |
Input: "00:02:20" and "00:04:40" | |
Output: "00:03:30" | |
Your answer will be evaluated based on: | |
* Working correctly for all possible input stopwatch times | |
* The clarity and simplicity of the solution | |
* The time taken - we would expect this task to take no more than 15-30 minutes | |
""" | |
import time | |
import datetime | |
import unittest | |
def split_to_delta(value): | |
# timedelta doesn't support strf* | |
mins, secs, msecs = value.split(":", 2) | |
return datetime.timedelta(minutes=int(mins), seconds=int(secs), | |
milliseconds=int(msecs)*10) | |
def calc_result(value1, value2): | |
t1 = split_to_delta(value1) | |
t2 = split_to_delta(value2) | |
total_secs = [ x.total_seconds() for x in (t1, t2)] | |
# mean average | |
avg_secs = (sum(total_secs) / len(total_secs)) | |
# annoyingly, timedelta doesn't have support for any of this | |
minutes, seconds = divmod(avg_secs, 60) | |
seconds, msecs = divmod(seconds, 1) | |
msecs = round(msecs * 100) | |
return "%02d:%02d:%02d" % ( minutes, seconds, msecs, ) | |
class TestStopwatch(unittest.TestCase): | |
def test_values(self): | |
# test seconds | |
result = calc_result("00:02:20", "00:04:40") | |
self.assertEquals(result, "00:03:30") | |
# test minutes | |
result = calc_result("02:00:20", "02:50:20") | |
self.assertEquals(result, "02:25:20") | |
# test microseconds partials | |
result = calc_result("00:00:01", "00:00:02") | |
self.assertEquals(result, "00:00:02") | |
# test microseconds | |
result = calc_result("00:00:01", "00:00:03") | |
self.assertEquals(result, "00:00:02") | |
# test microseconds 10ths | |
result = calc_result("00:00:20", "00:00:30") | |
self.assertEquals(result, "00:00:25") | |
# test hours | |
result = calc_result("69:00:20", "70:00:30") | |
self.assertEquals(result, "69:30:25") | |
# test days | |
result = calc_result("1000:00:20", "1050:00:30") | |
self.assertEquals(result, "1025:00:25") | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment