Skip to content

Instantly share code, notes, and snippets.

@thomie
Forked from dxlbnl/gist:5245302
Last active December 15, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomie/5247145 to your computer and use it in GitHub Desktop.
Save thomie/5247145 to your computer and use it in GitHub Desktop.
## Prelude.
from functools import partial
from itertools import chain, ifilter, islice, izip_longest
def compose(*funcs):
"""Return a function such that compose(a,b,c)(arg1, arg2, arg3)
is equivalent to a(b(c(arg1, arg2, arg3)))."""
# See http://bugs.python.org/issue1660179
def _composefunc(*args, **kw):
l = reversed(funcs)
rv = l.next()(*args, **kw)
for f in l:
rv = f(rv)
return rv
return _composefunc
def concat(xs):
return (y for x in xs for y in x)
concat_map = compose(concat, map)
def take(n, iterable):
return islice(iterable, n)
def drop(n, iterable):
return islice(iterable, n, None)
def splitat(n, xs):
return (take(n, xs), drop(n, xs))
def prepend(xs):
return partial(chain, xs)
def chunk(chunk_size, xs):
def _grouper(n, xs, fillvalue=None):
return izip_longest(*[iter(xs)]*n, fillvalue=fillvalue)
fillvalue = object()
xss = _grouper(chunk_size, xs, fillvalue)
return (ifilter(lambda x: x is not fillvalue, xs) for xs in xss)
## Solution.
def wrap_line(width, prefix, line):
head, tail = splitat(width, line)
return [head] + map(prepend(prefix), chunk(width - len(prefix), tail))
def wrap_lines(width, prefix, lines):
return concat_map(partial(wrap_line, width, prefix), lines)
## Hack.
normalize = ''.join
## Problem.
resp_lines = [
str(range(i)) for i in range(20, 50,3)
]
width = 80
prefix = " "
print '\n'.join(map(normalize, wrap_lines(width, prefix, resp_lines)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment