Last active
August 29, 2015 14:05
-
-
Save bluven/d160a8fe871e64deb233 to your computer and use it in GitHub Desktop.
reverse sentence
This file contains 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
#!/usr/bin/env python | |
# encoding: utf-8 | |
import array | |
def reverse_array(letters, start, end): | |
while start < end: | |
letters[start], letters[end] = letters[end], letters[start] | |
start += 1 | |
end -= 1 | |
def reverse_sentence(sentence): | |
a = array.array('c', sentence) | |
reverse_array(a, 0, len(a) - 1) | |
start = end = 0 | |
while end < len(a): | |
if a[end] not in (' ', ','): | |
end += 1 | |
continue | |
reverse_array(a, start, end-1) | |
end += 1 | |
start = end | |
reverse_array(a, start, end-1) | |
return a.tostring() | |
def reverse_sentence_with_stack(sentence): | |
sentence = sentence.split(' ') | |
reversed = [] | |
while sentence: | |
reversed.append(sentence.pop(-1)) | |
return ' '.join(reversed) | |
print reverse_sentence('test is test, that is true') | |
print reverse_sentence_with_stack('test is test, that is true') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment