Fastest Way To Reverse A String In Python
I was able to come up with two different ways to reverse a string in Python. Commonsense dictates that the more lines of code the slower it runs. I made the following lines of cod
Solution 1:
I see a difference.
First of all, what is up with map(lambda x: x, st)
? What is the purpose?
Use the timeit
module to test your code:
$ python -m timeit '"".join(reversed("abcdefghijklmnopqrstuvwxyz"))'
1000000 loops, best of 3: 0.586 usec per loop
$ python -m timeit '"abcdefghijklmnopqrstuvwxyz"[::-1]'
10000000 loops, best of 3: 0.0715 usec per loop
As you can see, the slice is ~8x faster on my machine for this particular input. It's also more concise.
Solution 2:
s=input("enter string")
print(s[::-1])
Post a Comment for "Fastest Way To Reverse A String In Python"