You can also do it with recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
And a simple example for the string hello:
reverse(hello)
= reverse(ello) + h # The recursive step
= reverse(llo) + e + h
= reverse(lo) + l + e + h
= reverse(o) + l + l + e + h # Base case
= o + l + l + e + h
= olleh
Answer from Blender on Stack OverflowYou can also do it with recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
And a simple example for the string hello:
reverse(hello)
= reverse(ello) + h # The recursive step
= reverse(llo) + e + h
= reverse(lo) + l + e + h
= reverse(o) + l + l + e + h # Base case
= o + l + l + e + h
= olleh
Just another option:
from collections import deque
def reverse(iterable):
d = deque()
d.extendleft(iterable)
return ''.join(d)
How do I reverse a string in Python? - Stack Overflow
python - Without using built-in functions, a function should reverse a string without changing the '$' position - Stack Overflow
python - Reversing words of a string without using inbuilt functions - Code Review Stack Exchange
How do you reverse a string without using built-in functions?
How to reverse a string in Python without a reverse function?
What is a reversed function in Python?
Can you use reverse () on a string?
Videos
Using slicing:
>>> 'hello world'[::-1]
'dlrow olleh'
Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings = []
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
Write functions
You show the reversal of two strings: John Doe and Happy new year! 2022. But your code can only reverse one string. If you wanted to reverse the other string as well, you'd have to duplicate the code.
Instead, write a function. They can be called multiple times.
def reverse_words(sentence):
... your code here ...
return final_str
str1 = "John Doe"
reversed1 = reverse_words(str1)
print(f"string: {str1}\nlen: {len(str1)}")
print(f"Reversed_string: {reversed1}\nlen: {len(reversed1)}")
str2 = "Happy new year! 2022"
reversed2 = reverse_words(str2)
print(f"string: {str2}\nlen: {len(str2)}")
print(f"Reversed_string: {reversed2}\nlen: {len(reversed2)}")
When writing functions, use type-hints and """doc-strings""" to provide additional information about how to use the function:
def reverse_words(sentence: str) -> str:
"""
Reverse the words of a string.
>>> reverse_words("John Doe")
'Doe John'
>>> reverse_words("Happy new year! 2022")
'2022 year! new Happy'
"""
... your code here ...
return final_str
With the above function definition, help(reverse_words) will describe the function in much the same way that help(print) describes the print function.
As a bonus, the >>> text in the """doc-string""" can be used for testing, via the doctest module.
Variable Naming
What is space_counter? At first read, I thought you were counting spaces, but it turns out that isn't quite correct:
space_counter = 0
for ...:
if char == " ":
space_counter += 1
if space_counter == 1:
...
elif space_counter == 2:
...
space_counter = 1
The "counter" starts at 0. At the first space, it increments to 1 and one action is performed. At the second and any subsequent space, it increments to 2 and is immediately reset to 1. Since it can only take on the values 0, 1 or 2, it is not really a counter.
It appears you are trying to do something different on the first space verses any subsequent space. A boolean "flag" is more descriptive in these cases:
seen_space = False
for ...:
if char == " ":
if not seen_space:
...
seen_space = True
else:
...
temp, a_str, and b_str are all similarly not descriptive variable names. final_str seems more descriptive, but it is used in statements like final_str = temp + " " + final_str, which means its value is not really "final", so again, it is not the best name either.
Iteration
for index in range(len(str1)):
char = str1[index]
...
Using range(len(...) in a for loop is frowned upon in polite Python circles. If index is required in the body of the loop, enumerate(...) is preferred:
for index, char in enumerate(str1):
...
Special cases
elif index == len(str1) - 1 is executed on every non-space iteration of the loop. If your string is very, very long, this could be a source of inefficiency. It is testing for the end of the string, which happens at the end of the loop. Why not move this end-of-loop code out of the loop?
for index in range(len(str1)):
...
if char == " ":
...
else:
temp += char
if temp != "":
if final_str != "":
final_str = temp + " " + final_str
else:
final_str = temp
Iteration (reprise)
By removing the index == len(str1) - 1 test in the loop body, we find we no longer need the index variable at all, so enumerate(...) is unnecessary, and the for loop can be simplified further:
for char in sentence:
...
Special cases (reprise)
Your code handles (and my above modification) has to handle the special case of a single word separately from multiple words. The reason is words end both with a subsequent space AND at the end of the string. We could work around this by intentionally adding a space at the end of the string ourselves, before processing begins.
str1 += " "
This additional sentinel guarantees words will always end with a space, and simplifies the code in the loop. Minor additional processing at the end may be necessary to remove the extra space in the output, depending on the exact implementation.
Not wanting to repeat what AJNeufeld has already said, I was curious how long it would take your code to reverse the full text of Moby Dick. While running this experiment, I noticed some funny behavior with spaces. For example, when your code is given " " (3 spaces), it returns " " (two spaces).
You might consider trying some quick tests such as these:
assert reverse_string("Happy new year! 2022") == "2022 year! new Happy"
assert reverse_string(" ") == " "
assert reverse_string(" ") == " "
assert reverse_string(" a") == "a "
assert reverse_string("a ") == " a"
assert reverse_string(" a ") == " a "
assert reverse_string(" a bc ") == " bc a "
assert reverse_string("nospacesinthisone") == "nospacesinthisone"
On my computer, by the way, your approach handles Moby Dick in about 14 seconds! When I initially tried to refactor your code, I achieved a similar result:
Refactor Attempt #1: 13-14 seconds
def reverse_string(string: str) -> str:
"""Reverse the words of a string.
>>> reverse_words('Happy new year! 2022')
'2022 year! new Happy'
"""
new_string, word = "", ""
for char in string:
if char == " ":
new_string = char + word + new_string
word = ""
else:
word += char
n_missing_chars = len(string) - len(new_string)
if n_missing_chars != 0:
new_string = string[-n_missing_chars:] + new_string
return new_string
Eventually, as you'll see below (if you try it), I managed to reduce the time to 0.1 seconds. It seems driven by replacing new = c + w + new with new += w + c. That this change would make things faster doesn't feel surprising, but I don't truly understand what is happening differently behind the scenes.
Refactor Attempt #2: 0.1 seconds
def reverse_string(string: str) -> str:
"""Reverse the words of a string.
>>> reverse_words('Happy new year! 2022')
'2022 year! new Happy'
"""
new_string, word = "", ""
for char in reversed(string):
if char == " ":
new_string += word[::-1] + char
word = ""
else:
word += char
n_missing_chars = len(string) - len(new_string)
if n_missing_chars != 0:
new_string += string[:n_missing_chars]
return new_string
While still adhering to your constraints, I wonder if there is a way to achieve similar or better performance than this without iterating through the string backwards.
Code Snippet: Trying Moby Dick yourself
If you want to reproduce the Moby Dick test yourself, you can use this snippet. You will need to save the full text of Moby Dick as a text file in the same directory as your Python script.
import time
with open("moby_dick.txt", "r") as f:
string = f.read()
start = time.time()
reversed_moby_dick = reverse_string(string)
end = time.time()
print(f"Execution time: {end - start: .1f} seconds")
As a final comment, were it not for your rules about "built-in functions of string", I likely would have tried using str.join at some point.
This has been a very fun exercise. Thank you for posting it!
You need to specify the length the ietarable ie, y.
z.append(y[len(y)-1-i])
Code:
z=[]
x=range(10)
def reve(y):
for i in range(len(y)):
z.append(y[len(y)-1-i])
return z
print reve(x)
Output:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
def rev(s):
s1=""
s2=""
for i in range(len(s)):
if s[i]!=" " and i!=len(s)-1:
s1+=s[i]
elif s[i]==" ":
s2+=s1[::-1]+" "
s1=""
else:
s1+=s[i]
s2+=s1[::-1]
return s2
if__name__="__main__"
s=input("Enter a sentense : ")
print("Sentence with individual reverse word : ",rev(s))