Fastest way to reverse a string in python

喜欢而已 提交于 2019-12-09 01:42:43

问题


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 code:

Code1

"".join(reversed(map(lambda x:x,st)))

Code2

st[::-1]

These give similar performance. For a 20000 long string I am not able to see a difference of even a millisecond in performance.

I think the first one should be a slower approach because it performs 3x more operations.

Question

Why am I not seeing a performance difference?


回答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.




回答2:


s=input("enter string")
print(s[::-1])


来源:https://stackoverflow.com/questions/36949665/fastest-way-to-reverse-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!