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]
Here is an O(n) implementation (doesn't use concatenation via
+
):This implements the split algorithm literally -- manually splitting the string into words, and then reversing the list of words.
Create a loop that iterates through the string backwards, using string indexing to get each character. Remember, in Python, you can access strings using the following:
Simplest program without using any built in methods :