Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> If Python were focused on functional programming it would have a utility function for this similar to itertools.groupby (but with indices in an array instead of keys in a dictionary).

itertools.groupby doesn’t return a dictionary, it returns an iterator of (key, (iterator that produces values)) tuples. It sounds, though, like you want something like:

  from itertools import groupby

  def categorize_into_list(source, _range, key):
    first = lambda x: x[0]
    sublist_dict = { 
      k: list(v[1] for v in vs) 
      for k, vs in groupby(sorted(((key(v), v) for v in source), key=first), first))
    }
    return [sublist_dict.get(i, []) for i in _range]
Then you could do this with something like:

  def congruent_sets(m, l):
    categorize_into_list(l, m, lambda v: v % m)


Yeah exactly.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: