Wednesday, May 23, 2012

How to Reverse Order of Words in Python

#!/usr/bin/env python

def reverse_words(string):
    reverse(string, 0, len(string)-1)
    
    prev_space_index = 0
    for i in xrange(0, len(string)):
        if string[i] == " ":
            reverse(string, prev_space_index, i-1)
            prev_space_index = i + 1

    # the last word hasn't been reversed    
    if prev_space_index < len(string):
        reverse(string, prev_space_index, len(string)-1)

def reverse(string, beg, end):
    i = beg
    j = end
#    print string[beg:end]
    while i < j:
        string[i], string[j] = string[j], string[i]
        i += 1
        j -= 1
    
if __name__ == "__main__":
    l = list("my first name is foo and my last name is bar")
    reverse_words(l)
    
    assert "bar is name last my and foo is name first my" == "".join(l)    

No comments:

Post a Comment