Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse word order of a string with no str.split() allowed

Tags:

python

string

What is the pythonic way to doing this?

From this: 'This is a string to try' to this: 'try to string a is This'

My first guess was:

for w in 'This is a string to try'.split(' ')[::-1]:
    print w,

but str.split() is not allowed. Then I came up with this:

def reverse_w(txt):
    tmp = []
    while (txt.find(' ') >= 0):
        tmp.append(txt[:txt.find(' ')])
        txt = txt[txt.find(' ')+1:]
    if (txt.find(' ') == -1):
        tmp.append(txt)
   return tmp[::-1]
like image 687
Stiggo Avatar asked Oct 08 '22 18:10

Stiggo


2 Answers

def reverse(sentence):
sentence = 'This is a string to try'
    answer = ''
    temp = ''
    for char in sentence:
        if char != ' ':
            temp += char
        else:
            answer = temp + ' ' + answer
            temp = ''
    answer = temp + ' ' + answer
    return answer.rstrip(' ')
like image 190
inspectorG4dget Avatar answered Oct 10 '22 08:10

inspectorG4dget


Here is an O(n) implementation (doesn't use concatenation via +):

def reverse_w(txt):
    words = []
    word = []

    for char in txt:
        if char == ' ':
            words.append(''.join(word))
            word = []
        else:
            word.append(char)
    words.append(''.join(word))

    return ' '.join(reversed(words))

This implements the split algorithm literally -- manually splitting the string into words, and then reversing the list of words.

like image 34
Casey Kuball Avatar answered Oct 10 '22 10:10

Casey Kuball