Guest User

Untitled

a guest
Jul 4th, 2015
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. import numpy as np
  2. import re
  3. import sys
  4. from collections import Counter
  5.  
  6.  
  7. def get_times_map(filename):
  8.     times_map = {}
  9.     with open(filename, 'r') as f:
  10.         lines = f.readlines()
  11.         for line in lines:
  12.             if line:
  13.                 split_line = re.split('\s+|,\s+', line.strip())
  14.                 name = split_line[0]
  15.                 times = []
  16.                 for time in split_line[1:]:
  17.                     if time:
  18.                         mins, seconds = re.split(':', time)
  19.                         times.append(60 * int(mins) + int(seconds))
  20.                 times_map[name] = times
  21.     return times_map
  22.  
  23. def decimal_round(x):
  24.     return "{0}".format(str(round(x, 1) if x % 1 else int(x)))
  25.  
  26. def seconds_to_time(seconds):
  27.     mins = str(int(seconds) / 60)
  28.     remaining_seconds = decimal_round(seconds % 60)
  29.     if ('.' not in remaining_seconds and len(remaining_seconds) < 2) or \
  30.         ('.' in remaining_seconds and remaining_seconds.index('.') == 1):
  31.         remaining_seconds = '0' + remaining_seconds
  32.     return '%s:%s' % (mins, remaining_seconds)
  33.  
  34. def print_stats(category, times, num_common=5):
  35.     min_time = seconds_to_time(min(times))
  36.     max_time = seconds_to_time(max(times))
  37.     avg_time = seconds_to_time(np.mean(times))
  38.     med_time = seconds_to_time(np.median(times))
  39.     variance = seconds_to_time(np.var(times))
  40.     print '%s: avg %s, median %s, min %s, max %s, variance %s [data points: %s]' % (
  41.         category, avg_time, med_time, min_time, max_time, variance, len(times))
  42.     if num_common:
  43.         counter = Counter(times)
  44.         sorted_times = sorted(counter, key=counter.get)
  45.         print 'Most common times:'
  46.         for time in reversed(sorted_times[-num_common:]):
  47.             print '\t%2s: %s' % (counter[time], seconds_to_time(time))
  48.         print 'Least common times:'
  49.         for time in sorted_times[:num_common]:
  50.             print '\t%2s: %s' % (counter[time], seconds_to_time(time))
  51.        
  52. def print_time_stats(filename):
  53.     times_map = get_times_map(filename)
  54.     for category in times_map:
  55.         print_stats(category, times_map[category])
  56.  
  57. if __name__=='__main__':
  58.     if len(sys.argv) != 2:
  59.         print 'Usage: time_stats.py [input file]'
  60.     else:
  61.         print_time_stats(sys.argv[1])
Advertisement
Add Comment
Please, Sign In to add comment