Last active
August 29, 2015 14:15
-
-
Save realeroberto/1e7a9dad2ee1419dc4d3 to your computer and use it in GitHub Desktop.
Given text and a desired line length, wrap the text as a typewriter would...
This file contains hidden or 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
# Given text and a desired line length, wrap the text as a typewriter would. | |
# An exercise from MITx: 6.00.1x Introduction to Computer Science and Programming Using Python. | |
def typewriter(text, lineLength): | |
""" | |
Given text and a desired line length, wrap the text as a typewriter would. | |
Insert a newline character ("\n") after each word that reaches or exceeds | |
the desired line length. | |
text: a string containing the text to wrap. | |
line_length: the number of characters to include on a line before wrapping | |
the next word. | |
returns: a string, with newline characters inserted appropriately. | |
""" | |
def insertNewlinesRecur(wordList, remainingLineLength): | |
if not wordList or len(wordList) == 0: | |
return "" | |
else: | |
word = wordList[0] | |
if len(wordList) > 1: | |
wordList = wordList[1:] | |
else: | |
wordList = None | |
if len(word) > remainingLineLength: | |
return word + "\n" + insertNewlinesRecur(wordList, lineLength) | |
else: | |
remainingLineLength -= len(word) + 1 | |
return word + " " + insertNewlinesRecur(wordList, remainingLineLength) | |
if not text: | |
return None | |
else: | |
return insertNewlinesRecur(text.split(), lineLength) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment