Last active
December 15, 2015 15:18
-
-
Save kachayev/5280327 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # 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