I\'m trying to write the Haskel function \'splitEvery\' in Python. Here is it\'s definition:
splitEvery :: Int -> [e] -> [[e]]
@\'splitEvery\' n@ s
I think those questions are almost equal
Changing a little bit to crop the last, I think a good solution for the generator case would be:
from itertools import *
def iter_grouper(n, iterable):
it = iter(iterable)
item = itertools.islice(it, n)
while item:
yield item
item = itertools.islice(it, n)
for the object that supports slices (lists, strings, tuples), we can do:
def slice_grouper(n, sequence):
return [sequence[i:i+n] for i in range(0, len(sequence), n)]
now it's just a matter of dispatching the correct method:
def grouper(n, iter_or_seq):
if hasattr(iter_or_seq, "__getslice__"):
return slice_grouper(n, iter_or_seq)
elif hasattr(iter_or_seq, "__iter__"):
return iter_grouper(n, iter_or_seq)
I think you could polish it a little bit more :-)