diff --git a/justify.py b/justify.py index 96503d9cc75dfdbda2a2af62449db1632424bfee..d169fa00e177af2e113a19e88b7ba7923ea58306 100755 --- a/justify.py +++ b/justify.py @@ -29,13 +29,12 @@ Array [7] = "actually works.†""" import sys + def justify_text(text, width): - """Justify text to width and return a list of strings.""" + """Justify text to width, generate strings.""" wordlist = text.split() - # Build a list of lines that will fit in justified format with room for - # at least one space between each word. - lines = [] + # Generate Justified lines that will fit in justified line = [] length = 0 for word in wordlist: @@ -44,7 +43,7 @@ def justify_text(text, width): line.append(word) length += wordlen else: - lines.append(line) + yield(apply_spacing(line, width)) line = [] line.append(word) length = wordlen @@ -55,28 +54,26 @@ def justify_text(text, width): # Handles last line, and single word lines if line: - lines.append(line) - - apply_spacing(lines, width) - return lines + yield(apply_spacing(line, width)) -def apply_spacing(lines, width): - """Space out each line to meet the width requirements.""" - for i, line in enumerate(lines): - llen = sum([len(word) for word in line]) +def apply_spacing(line, width, prepad=True): + """Space out a line to meet the width requirements.""" + llen = sum([len(word) for word in line]) - if len(line)-1: - joinspaces = ' ' * ((width - llen) // (len(line)-1)) - extraspace = ' ' * ((width - llen) % (len(line)-1)) - else: - joinspaces = '' - extraspace = ' ' * (width - llen) + if len(line)-1: + joinspaces = ' ' * ((width - llen) // (len(line)-1)) + extraspace = ' ' * ((width - llen) % (len(line)-1)) + else: + joinspaces = '' + extraspace = ' ' * (width - llen) - # line[0] += extraspace + if prepad: line[-1] = extraspace + line[-1] + else: + line[0] += extraspace - lines[i] = joinspaces.join(line) + return joinspaces.join(line) def show_justified_text_as_array_lines(justified_text): @@ -86,8 +83,7 @@ def show_justified_text_as_array_lines(justified_text): def main(): - """Accept text string and page width and output array list of justified - text.""" + """Accept text string and page width, output justified text.""" if len(sys.argv) == 3: paragraph = sys.argv[1] page_width = int(sys.argv[2]) @@ -96,8 +92,7 @@ def main(): solved, so we are adding more text to see that it actually works.""" page_width = 20 - justified_text = justify_text(paragraph, page_width) - show_justified_text_as_array_lines(justified_text) + show_justified_text_as_array_lines(justify_text(paragraph, page_width)) if __name__ == '__main__':