Last active
August 29, 2015 14:15
-
-
Save elvinio/9de2ae0da183cf83c38f to your computer and use it in GitHub Desktop.
Reverse string in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]'