# 6.00x Problem Set 5
#
# Part 2 - RECURSION

#
# Problem 3: Recursive String Reversal
#

def reverseString(aStr, soFar=''):
    """
    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 aStr == '':
        return soFar
    else: return reverseString(aStr[:-1], soFar + aStr[-1] )


#
# Problem 4: Erician
#
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 x == '': return True
    else:
        try:        
            index = word.index(x[0])
            return x_ian(x[1:], word[index:])
        except ValueError:
            return False

#
# Problem 5: Typewriter
#
def insertNewlines(text, lineLength, lengthSoFar=0):
    """
    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. 
    """
    if text == '': return ''
    try:
        index = text.index(' ') + 1        
        lengthSoFar += len(text[:index])
        addToLine = text[:index]
        newText = text[index:]
    except ValueError:
        newText = ''
        addToLine = text

    if lengthSoFar >= lineLength:
        addToLine += '\n'
        lengthSoFar = 0
    return addToLine + insertNewlines(newText, lineLength, lengthSoFar)

print insertNewlines('While I expect new intellectual adventures ahead, nothing will compare to the exhilaration of the world-changing accomplishments that we produced together.', 15)
print insertNewlines('Nuh-uh! We let users vote on comments and display them by number of votes. Everyone knows that makes it impossible for a few persistent voices to dominate the discussion.', 20)
