Skip to content

Instantly share code, notes, and snippets.

@nafu
Created March 19, 2013 11:59
Show Gist options
  • Save nafu/5195522 to your computer and use it in GitHub Desktop.
Save nafu/5195522 to your computer and use it in GitHub Desktop.
# 6.00x Problem Set 5
#
# Part 2 - RECURSION
#
# Problem 3: Recursive String Reversal
#
def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are indexing,
slicing, and concatenation.
aStr: a string
returns: a reversed string
"""
if len(aStr) <= 1:
return aStr
else:
first = aStr[0]
mid = aStr[1:-1]
end = aStr[-1]
return end+reverseString(mid)+first
#
# Problem 4: X-ian
#
def x_ian(x, word):
"""
Given a string x, returns True if all the letters in x are
contained in word in the same order as they appear in x.
>>> x_ian('eric', 'meritocracy')
True
>>> x_ian('eric', 'cerium')
False
>>> x_ian('john', 'mahjong')
False
x: a string
word: a string
returns: True if word is x_ian, False otherwise
"""
if len(x) < 1:
return Fasle
if len(x) == 1:
return x in word
else:
return x[0] in word and x_ian(x[1:], word.split(x[0], 1)[1])
#
# Problem 5: Typewriter
#
def insertNewlines(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.
"""
return insertNewlinesRec(text, lineLength)
def insertNewlinesRec(text, lineLength):
import string
words = text.split(' ')
wordcount = 0
wordindex = 0
for word in words:
wordcount += (len(word)+1)
if wordcount >= lineLength:
before_text = string.join(words[:(wordindex+1)])
next_text = string.join(words[wordindex+1:])
return before_text+'\n'+insertNewlinesRec(next_text, lineLength)
wordindex += 1
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment