Skip to content

Commit

Permalink
Add unpythonic.it.pad: extend iterable to length n with fillvalue
Browse files Browse the repository at this point in the history
  • Loading branch information
Technologicat committed Aug 22, 2019
1 parent 8bb8fd9 commit 16e683b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 16 additions & 1 deletion unpythonic/it.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"unpack",
"tail", "butlast", "butlastn",
"first", "second", "nth", "last", "lastn",
"scons",
"scons", "pad",
"flatten", "flatten1", "flatten_in",
"iterate", "iterate1",
"partition",
Expand Down Expand Up @@ -462,6 +462,21 @@ def scons(x, iterable):
"""
return chain((x,), iterable)

def pad(n, fillvalue, iterable):
"""Pad iterable with copies of fillvalue so its length is at least ``n``.
Examples::
assert tuple(pad(5, None, range(3))) == (0, 1, 2, None, None)
assert tuple(pad(5, None, ())) == (None, None, None, None, None)
assert tuple(pad(5, None, range(6))) == tuple(range(6))
"""
k = 0 # used if iterable is empty
for k, x in enumerate(iterable, start=1):
yield x
for _ in range(k, n):
yield fillvalue

def flatten(iterable, pred=None):
"""Recursively remove nested structure from iterable.
Expand Down
6 changes: 5 additions & 1 deletion unpythonic/test/test_it.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
map_longest, mapr_longest, rmap_longest, \
zip_longest, zipr_longest, rzip_longest, \
first, second, nth, last, lastn, \
scons, tail, butlast, butlastn, \
scons, pad, tail, butlast, butlastn, \
flatmap, \
take, drop, split_at, \
rev, \
Expand Down Expand Up @@ -70,6 +70,10 @@ def noneadd(a, b):
assert tuple(scons(0, range(1, 5))) == tuple(range(5))
assert tuple(tail(scons("foo", range(5)))) == tuple(range(5))

assert tuple(pad(5, None, range(3))) == (0, 1, 2, None, None)
assert tuple(pad(5, None, ())) == (None, None, None, None, None)
assert tuple(pad(5, None, range(6))) == tuple(range(6))

assert tuple(butlast(range(5))) == (0, 1, 2, 3)
assert tuple(butlastn(3, range(5))) == (0, 1)

Expand Down

0 comments on commit 16e683b

Please sign in to comment.