function gini(labels):

   total = length(labels)
   impurity = 1
   for label in distinct(labels):
      p = count(labels, label) / total
      impurity -= p ** 2
   return impurity      # 0 = pure, higher = more mixed


 function best_split(data, feature_candidates):
   return argmin(feature_candidates, key=lambda f: weighted_gini_after_split(data,
 f))
