runnig

[hackerrank] ML basic statistics warmup

Jun 26th, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import sys, collections, math
  3.  
  4. def mean(A):
  5.     S = sum(A)
  6.     N = len(A)
  7.     return float(S) / float(N) if N > 0 else 0.0
  8.  
  9. def median(A):
  10.     N = len(A)    
  11.     A_sorted = sorted(A)
  12.     if N%2 != 0:
  13.         ret = A_sorted[N/2]
  14.     else:
  15.         ret = float(A_sorted[N/2] + A_sorted[N/2-1])/2.0
  16.     return ret
  17.  
  18. COUNT = 0
  19. VALUE = 1
  20.  
  21. def mode_freq_cmp(v1, v2):
  22.     if v1[COUNT] != v2[COUNT]:
  23.         return v2[COUNT] - v1[COUNT]
  24.     else:
  25.         return v1[VALUE] - v2[VALUE]
  26.  
  27. def mode(A):    
  28.     freq = collections.defaultdict(int)
  29.    
  30.     for v in A:
  31.         freq[v] += 1
  32.    
  33.     freq_list = [(count, value) for value, count in freq.iteritems()]
  34.     freq_list.sort(cmp=mode_freq_cmp)
  35.    
  36.     return freq_list[0][VALUE]
  37.    
  38. def stdev(A):
  39.     N = len(A)
  40.     M = mean(A)
  41.     S = 0
  42.     for v in A:
  43.         d = v - M
  44.         S += d * d
  45.     return math.sqrt( S / N )
  46.  
  47. def confidence_interval(A, Mean, Stdev, confidence=0.95):
  48.     v = 1.96 *  Stdev / math.sqrt(len(A))
  49.     return Mean - v, Mean + v
  50.        
  51. def main(A):
  52.     Mean, Median, Stdev = mean(A), median(A), stdev(A)
  53.     conf_intervals = confidence_interval(A, Mean, Stdev)
  54.     print '%.1f' % Mean
  55.     print '%.1f' % Median
  56.     print '%d'   % mode(A)
  57.     print '%.1f' % Stdev
  58.     print '%.1f %.1f' % (conf_intervals[0], conf_intervals[1])
  59.  
  60. if __name__ == '__main__':
  61.     N = int(input())
  62.     A = [int(v) for v in sys.stdin.readline().split(' ')]
  63.     #A = [int(v) for v in "64630 11735 14216 99233 14470 4978 73429 38120 51135 67060".split()]
  64.     main(A)
Add Comment
Please, Sign In to add comment