Last active
August 29, 2015 14:15
-
-
Save realeroberto/dfd7a3e9fd562ad7811f to your computer and use it in GitHub Desktop.
Recursive String Reversal in Python.
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
# 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