Skip to content

Instantly share code, notes, and snippets.

@kachayev
Last active December 15, 2015 15:18
Show Gist options
  • Save kachayev/5280327 to your computer and use it in GitHub Desktop.
Save kachayev/5280327 to your computer and use it in GitHub Desktop.
# python 2+
from itertools import takewhile, ifilter, izip, tee, starmap, chain
def uniq_substrings(origin):
suffixes = chain([""], sorted(tails(origin)))
return sum(starmap(suffix, pairwise(suffixes)))
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def common_prefix(pre, post):
return takewhile(lambda (k1, k2): k1==k2, izip(pre, post))
def suffix(pre, post):
return len(post) - ilen(common_prefix(pre, post))
def tails(origin):
return (origin[i:] for i in xrange(ilen(origin)))
def ilen(iterable):
return sum(1 for it in iterable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment