Comment by ummonk
4 years ago
Why not just use a list comprehension?
def congruent_sets(m, l):
return [[v for v in l if v % m == i] for i in range(m)]
4 years ago
Why not just use a list comprehension?
def congruent_sets(m, l):
return [[v for v in l if v % m == i] for i in range(m)]
Isn't that unnecessary quadratic algorithm (nested loops, m*l iterations, instead of m + l)?
Yes, but that's the case with all the functional approaches proposed.
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).
> 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:
Then you could do this with something like:
1 reply →