-
-
Save thomie/5247145 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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