Skip to content

Instantly share code, notes, and snippets.

@johnpaulhayes
Created October 18, 2013 10:34
Show Gist options
  • Save johnpaulhayes/7039677 to your computer and use it in GitHub Desktop.
Save johnpaulhayes/7039677 to your computer and use it in GitHub Desktop.
python implementation to reverse a string
'''
@desc: An algorithm to reverse a list of characters.
@param: A list of characters.
'''
def reverse_algorithm(my_string):
length_of_string, i, reversed_string = len(my_string), 0, []
while i < length_of_string:
reversed_string.append(my_string[length_of_string-1-i])
i += 1
return reversed_string
'''
@param: the string to be reversed
@param: flag to indicate weither to use the inbuilt reverse
mechanism or not.
'''
def reverse_string(my_string, built_in_mechanism=False):
# Convert the string to a list for easy of manipulation
my_string = list(my_string)
if built_in_mechanism is True:
return my_string[::-1]
else:
return reverse_algorithm(my_string)
print reverse_string('reverseme', False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment