title: Python - Create a hierarchy based on a flat list of values that add up to 100
body: <p>I have a list (an OrderedDict, technically), that I need as a hierarchy based on the values that consecutively add up to 100.  For example:</p>
  
  <pre><code>&gt;&gt;&gt; a = OrderedDict([('1', 60), ('2', 15), ('3', 50), ('4', 40), ('5', 10), ('6', 85), ('7', 40)])
  &gt;&gt;&gt; a
  OrderedDict([('1', 60),
               ('2', 15),
               ('3', 50),
               ('4', 40),
               ('5', 10),
               ('6', 85),
               ('7', 40)])
  </code></pre>
  
  <p>I want to create a hierarchy like this:</p>
  
  <pre><code>'1': [
        '2': ['3', '4', '5'],
        '6': []
       ], 
  '7': []
  </code></pre>
  
  <p>where 1 + 7 add up to 100, 2 + 6 add up to 100, and 3 + 4 + 5 add up to 100.  Values can be repeated; for example, at worst it could look like:</p>
  
  <pre><code>OrderedDict([('1', 50),
               ('2', 50),
               ('3', 50),
               ('4', 50)])
  </code></pre>
  
  <p>At which point, any guess will do; this is overall unlikely.</p>
  
  <p>I figured it's a relatively straightforward recursive function, but I can't figure out where to restart.  I tried this:</p>
  
  <pre><code>keys = list(a.keys())
  l = []
  c = 0
  full = {}
  def get_split_vars(full, curr_keys):
      l = []
      c = 0
      for i in range(0, len(curr_keys)):
          if c + a[curr_keys[i]] &lt; 100:    # if less than 100, keep trying
              c += a[curr_keys[i]]
              l.append(curr_keys[i])
          elif c + a[curr_keys[i]] &gt; 100:  # if more than 100, reset
              c = a[curr_keys[i]]
              l = [curr_keys[i]]
          elif c + a[curr_keys[i]] == 100: # if 100, this is a grouping, take it out of the full set
              l.append(curr_keys[i])
              full[curr_keys[i - len(l)]] = l
              new_keys = [curr_keys[x] for x in range(0, len(curr_keys)) if curr_keys[x] not in l]
      return full, new_keys
  
  while keys:
      full, keys = get_split_vars(full, keys)
  </code></pre>
  
  <p>which, as expected, gets the middle grouping (3, 4, and 5), but chokes at the smaller grouping - where it resets to '6' (85), rather than what I'd actually want ('2').  I can't figure out where to modify the function, but it seems like I'm missing something simple.  Thanks in advance!</p>