Skip to content

Instantly share code, notes, and snippets.

@realeroberto
Last active August 29, 2015 14:15
Show Gist options
  • Save realeroberto/1e7a9dad2ee1419dc4d3 to your computer and use it in GitHub Desktop.
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...
# 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