Skip to content

Instantly share code, notes, and snippets.

@deniszh
Created October 22, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deniszh/1e7eb64cb372d83d9ecd46d11c813193 to your computer and use it in GitHub Desktop.
Save deniszh/1e7eb64cb372d83d9ecd46d11c813193 to your computer and use it in GitHub Desktop.
import timeit
import re
EXPAND_BRACES_RE = re.compile(r'.*(\{.+?[^\\]\})')
def expand_braces_new(s):
res = list()
m = EXPAND_BRACES_RE.search(s)
if m is not None:
sub = m.group(1)
open_brace = s.find(sub)
close_brace = open_brace + len(sub) - 1
if sub.find(',') != -1:
for pat in sub.strip('{}').split(','):
res.extend(expand_braces_new(s[:open_brace] + pat + s[close_brace + 1:]))
else:
res.extend(expand_braces_new(s[:open_brace] + sub.replace('}', '\\}') + s[close_brace + 1:]))
else:
res.append(s.replace('\\}', '}'))
return list(set(res))
def expand_braces_orig(orig):
r = r'.*(\{.+?[^\\]\})'
p = re.compile(r)
s = orig[:]
res = list()
m = p.search(s)
if m is not None:
sub = m.group(1)
open_brace = s.find(sub)
close_brace = open_brace + len(sub) - 1
if sub.find(',') != -1:
for pat in sub.strip('{}').split(','):
res.extend(expand_braces_orig(s[:open_brace] + pat + s[close_brace + 1:]))
else:
res.extend(expand_braces_orig(s[:open_brace] + sub.replace('}', '\\}') + s[close_brace + 1:]))
else:
res.append(s.replace('\\}', '}'))
return list(set(res))
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
s='foo.{ba{r,z},baz}.baz'
wrapped_orig = wrapper(expand_braces_orig, s)
wrapped_new = wrapper(expand_braces_new, s)
print timeit.timeit(wrapped_orig, number=100000)
print timeit.timeit(wrapped_new, number=100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment