a sequence question
Nick Coghlan
ncoghlan at iinet.net.au
Tue Feb 1 22:07:01 EST 2005
Steven Bethard wrote:
> I think you can write that second one so that it works for iterables
> without a __len__:
>
> py> def padded_partition(iterable, part_len, pad_val=None):
> ... itr = itertools.chain(
> ... iter(iterable), itertools.repeat(pad_val, part_len - 1))
> ... return itertools.izip(*[itr]*part_len)
> ...
> py> list(padded_partition(itertools.islice(itertools.count(), 10), 2))
> [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
> py> list(padded_partition(itertools.islice(itertools.count(), 10), 3))
> [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
>
> I just unconditionally pad the iterable with 1 less than the partition
> size... I think that works right, but I haven't tested it any more than
> what's shown.
I think you're right - I was looking at padding unconditionally, but because I
was padding with the actual partition length, it didn't work correctly when the
padding wasn't needed.
Padding with one less than the partition length fixes that quite neatly.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list