Facebook
From Amayo Mordecai, 3 Years ago, written in Python.
Embed
Download Paste or View Raw
Hits: 64
  1. from sys import stdin,stdout
  2.  
  3.  
  4. def filter_data(data):
  5.         ranges = ["[0, 0.2)", "[0.2, 0.4)", "[0.4, 0.6)",
  6.                         "[0.6, 0.8)", "[0.8, 1.0)"]
  7.  
  8.         group = {}
  9.  
  10.         # group the data
  11.         for val in data:
  12.                 idx = ranges[int(val/0.2)]
  13.  
  14.                 group.setdefault(idx,{})
  15.                 group[idx].setdefault("items",[])
  16.                 group[idx].setdefault("count", 0)
  17.  
  18.                 group[idx]["items"].append(val)
  19.                 group[idx]["count"] += 1
  20.  
  21.         # check if a cartegory doesn't have a value
  22.         if len(group.keys()) < len(ranges):
  23.                 return [None]
  24.  
  25.  
  26.         # find the minumin number of items in a cartegory
  27.         minumum = min(group.values(), key=lambda x:x["count"])["count"]
  28.  
  29.         # create thhe balanced dataset by picking the minumun
  30.         # number of items in each cartegory
  31.         filtered = []
  32.         for k in group.values():
  33.                 filtered.extend(k['items'][:minumum])
  34.  
  35.         return filtered
  36.  
  37. #read the data from stdin
  38. data = [float(num.rstrip()) for num in stdin.readlines()[0].split(",")]
  39.  
  40. filtered_data = filter_data(data)
  41.  
  42. #output the filtered data
  43. stdout.write(", ".join(map(str,filtered_data)))