Created
June 7, 2012 14:44
-
-
Save anonymous/2889181 to your computer and use it in GitHub Desktop.
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
def strtr_kojiro(strng, replace): | |
if replace and strng: | |
s, r = replace.popitem() | |
return r.join(strtr_kojiro(subs, dict(**replace)) for subs in strng.split(s)) | |
return strng | |
def strtr_aix(s, repl): | |
pattern = '|'.join(map(re.escape, sorted(repl.keys(), key=len, reverse=True))) | |
return re.sub(pattern, lambda m:repl[m.group(0)], s) | |
def strtr_gumbo(strng, replace): | |
buffer = [] | |
i, n = 0, len(strng) | |
while i < n: | |
match = False | |
for s, r in replace.items(): | |
if strng[i:len(s)+i] == s: | |
buffer.append(r) | |
i = i + len(s) | |
match = True | |
break | |
if not match: | |
buffer.append(strng[i]) | |
i = i + 1 | |
return ''.join(buffer) | |
def strtr_thg(strng, replace): | |
buffer, i = [], 0 | |
while i < len(strng): | |
for s, r in replace.items(): | |
if strng[i:len(s)+i] == s: | |
buffer.append(r) | |
i += len(s) | |
break | |
else: | |
buffer.append(strng[i]) | |
i += 1 | |
return ''.join(buffer) | |
import re | |
funcs = [x for x in dir() if x.startswith('strtr')] | |
# make sure everything works fine | |
for f in funcs: | |
j = globals()[f]('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}) | |
assert j == 'bbz-x-y', f | |
j = globals()[f]('aa-bb-cc' * 10, {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}) | |
assert j == 'bbz-x-y' * 10, f | |
from timeit import timeit | |
setup = 'from __main__ import ' + ','.join(funcs) | |
# test with a short subject (thg wins) | |
s = 'aa-bb-cc' | |
r = {'aa': 'bbz', 'bb': 'x', 'cc': 'y'} | |
times = [(timeit("%s(%r,%r)" % (f, s, r), setup, number=5000), f) for f in funcs] | |
for p in sorted(times): | |
print '%.4f %s' % p | |
# test with a longer subject (aix wins) | |
s = 'aa-bb-cc' * 10 | |
r = {'aa': 'bbz', 'bb': 'x', 'cc': 'y'} | |
times = [(timeit("%s(%r,%r)" % (f, s, r), setup, number=5000), f) for f in funcs] | |
for p in sorted(times): | |
print '%.4f %s' % p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment