I want understand how this word wrap program playing on input
rosuav at gmail.com
Thu Apr 4 15:19:03 EDT 2019
On Fri, Apr 5, 2019 at 6:16 AM MRAB <python at mrabarnett.plus.com> wrote:
> On 2019-04-04 19:53, David Raymond wrote:
> > The function is constructing a list of the lines, which it will combine at the end. Answering the questions in reverse order:
> > 3. Also why that `if` test is required there.
> > The if statement is saying "I don't have room on my current line for the next word, so time to start a new line"
> > 2. In the if clause why `current_line_length` is set back to 0 every time the condition is true.
> > current_line_length is, well, the length of the current line. Where it's set to 0 is when you've just started a new line, so it's saying "I'm now on a new line and have used up 0 characters so far on that line"
> > 1. why `line_length` is set to `current_line_length` initially?
> > lines_of_words starts out empty. Setting current_line_length to line_length triggers the "hey, I need to make a new line" on the first word, effectively creating the first line.
> > Also, I feel like there's a bug in this, where
> > current_line_length += len(word)
> > should be...
> > current_line_length += (len(word) + 1)
> > Otherwise the line length doesn't count the spaces. And a lot of little words will result in longer lines than you asked for.
> Yep, spotted that too! :-) BTW, your fix also a bug: the last word on a
> line won't be followed by a space (off-by-one). The easiest fix for that
> is to add 1 to line_length initially, another little trick.
Or, equivalently, to reset current_line_length to -1, which is an elegant hack.
More information about the Python-list