Since Python strings are immutable, we'll use a list of words instead to exercise in-place string manipulation as you would get with a C string.
create a list as a string builder for reversed sentence
In [28]:
def reverse_words(string):
if not string:
return string
newString = []
for word in string.split():
newWord = []
for char in word:
newWord.insert(0, char)
newString.insert(0, "".join(newWord))
return " ".join(newString)
In [24]:
def reverse_words2(string):
string = list(string)
string.reverse()
return "".join(string)
def reverse_words3(string):
return string[::-1]
In [23]:
from nose.tools import assert_equal
def testWith(func):
assert_equal(reverse_words("this is an Example."), ".elpmaxE na si siht")
assert_equal(reverse_words("hello friend"), "dneirf olleh")
assert_equal(reverse_words("COOL"), "LOOC")
assert_equal(reverse_words(None), None)
print('Success: reverse_words')
testWith(reverse_words)
testWith(reverse_words2)
testWith(reverse_words3)
In [27]:
import timeit
print "reverse_words", timeit.timeit(
"reverse_words('this is an Example.')",
"from __main__ import reverse_words", number=99000)
print "reverse_words2", timeit.timeit(
"reverse_words2('this is an Example.')",
"from __main__ import reverse_words2", number=99000)
print "reverse_words3", timeit.timeit(
"reverse_words3('this is an Example.')",
"from __main__ import reverse_words3", number=99000)
In [2]:
print "hellasdasd"
In [ ]: