#!/usr/bin/python
from string import join
import re
def reverse_string(s):
""" Does a simple character-based reverse of a string.
This could alternatively be done by calling reverse_chars below,
but it showcases a different method of reversing the string. """
splitter = re.compile(r'\s')
list = splitter.split(s)
space = ' '
list.reverse()
out = join(list, ' ')
return out
def reverse_chars(s, l):
""" Reverse the first l characters of string s. """
p1 = 0
p2 = l - 1
while p1 != p2:
t = s[p1]
s[p1] = s[p2]
s[p2] = t
p1 = p1 + 1
p2 = p2 - 1
def reverse_string_in_place(s):
""" 'Clever' algorithm for reversing a string in place.
Step 1: Reverse the string, character by character.
Step 2: Reverse each word
"""
reverse_chars(s, len(s))
c = 0
while c < len(s):
p1 = c
p2 = c
while s[p2] != " " and p2 < len(s):
p2 = p2 + 1
reverse_chars(p1, p2)
c = p2 + 1
s = "These are words in a string"
print reverse_string(s)