Skip to content

Instantly share code, notes, and snippets.

@realeroberto
Last active August 29, 2015 14:15
Show Gist options
  • Save realeroberto/dfd7a3e9fd562ad7811f to your computer and use it in GitHub Desktop.
Save realeroberto/dfd7a3e9fd562ad7811f to your computer and use it in GitHub Desktop.
Recursive String Reversal in Python.
# Recursively returns a reversed copy of the given string.
# An exercise from MITx: 6.00.1x Introduction to Computer Science and Programming Using Python.
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
"""
def reverseStringRecur(aStr):
if not aStr or len(aStr) == 0:
return aStr
else:
return aStr[-1] + reverseString(aStr[0:-1])
if type(aStr) == type(""):
return reverseStringRecur(aStr)
else:
raise TypeError("`aStr' must be a string!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment