daily pastebin goal
66%
SHARE
TWEET

Untitled

a guest Jun 24th, 2018 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. array = [1.0, 1.2, 0.4, ...] # A bunch of numbers
  2. counts = {}
  3. for a in array:
  4.   if a in counts:
  5.     counts[a] += 1
  6.   else:
  7.     counts[a] = 1
  8.    
  9. sorted([(v, k) for k, v in counts.items()])[-1][1]
  10.    
  11. NB. random array of floating-point numbers
  12.    ] y =: 10 (?@$%]) 5
  13. 0 0.6 0.2 0.4 0.4 0.8 0.6 0.6 0.8 0
  14.    NB. count occurrences
  15.    ({:,#)/.~ y
  16.   0 2
  17. 0.6 3
  18. 0.2 1
  19. 0.4 2
  20. 0.8 2
  21.    NB. order by occurrences
  22.    (:{:"1)({:,#)/.~ y
  23. 0.6 3
  24.   0 2
  25. 0.4 2
  26. 0.8 2
  27. 0.2 1
  28.    NB. pick the most frequent
  29.    {.{.(:{:"1)({:,#)/.~ y
  30. 0.6
  31.    
  32. epsilon = 0.0001
  33. def almost_equal(a, b):
  34.     return -epsilon <= a-b <= epsilon
  35.  
  36. array = [0.0, 0.6, 0.2, 0.4, 0.4, 0.8, 0.6, 0.6, 0.8, 0.0]
  37.  
  38. # more efficient would be to keep this in sorted order,
  39. # and use binary search to determine where to insert,
  40. # but this is just a simple demo
  41. counts = []
  42. for a in array:
  43.     for i, (b, c) in enumerate(counts):
  44.         if almost_equal(a, b):
  45.             counts[i] = (b, c + 1)
  46.             break
  47.     else:
  48.         counts.append((a, 1))
  49.  
  50. # sort by frequency, extract key of most frequent
  51. print "Mode is %f" % sorted(counts, key = lambda(a, b): b)[-1][0]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top