Skip to content

Instantly share code, notes, and snippets.

@elvinio
Last active August 29, 2015 14:15
Show Gist options
  • Save elvinio/9de2ae0da183cf83c38f to your computer and use it in GitHub Desktop.
Save elvinio/9de2ae0da183cf83c38f to your computer and use it in GitHub Desktop.
Reverse string in python
#!/usr/bin/env python
# iterative
string = "testing"
newstring = ""
for s in string[:]:
newstring = s + newstring
print newstring
# recursive
def rev(n):
if len(n) == 1:
return n
else:
return rev(n[1:]) + n[:1]
print rev(string)
# native step
string[::-1]
@elvinio
Copy link
Author

elvinio commented Mar 5, 2015

Recursive: 10000 loops, best of 3: 28.7 usec per loop
Iterative: 100000 loops, best of 3: 7.92 usec per loop
Native step: 100000000 loops, best of 3: 0.0189 usec per loop

python -mtimeit -s'import revrec' 'revrec.rev("/usr/src/kernels/3.10.0-121.el7.x86_64/include/config/bt/bnep/proto/filter.h")'

python -mtimeit -s'import rev' 'rev.rev()'

python -m timeit -s 'str="/usr/src/kernels/3.10.0-121.el7.x86_64/include/config/bt/bnep/proto/filter.h"; str[::-1]'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment