Created
March 21, 2013 21:38
-
-
Save nboubakr/5217045 to your computer and use it in GitHub Desktop.
Enumerate a string to substrings
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
#!/usr/bin/env python | |
#! -*- coding: utf-8 -*- | |
# Enumerate a string to substrings | |
# Y is a substring for X if: X = U.Y.V | |
def enumerate(string): | |
"""Function that will enumerate a string to substring | |
return: A list with all the substrings | |
>>> enumerate(aabccb) | |
result = ( , a, c, b, abcc, abc, bc, cc, cb, aabc, aab, bccb, aa, bcc, ab, abccb, aabcc, aabccb, ccb) | |
""" | |
prefix = list() | |
root = list() | |
suffix = list() | |
result = list() | |
for i in range(len(string)): | |
prefix.append(string[:i]) | |
root.append(string[i:]) | |
root.append(string[:i]) | |
suffix.append(string[:i]) | |
for j in range(len(string)): | |
prefix.append(string[i:j]) | |
root.append(string[j:]) | |
root.append(string[i:j]) | |
# Append prefix, root and suffix to the result list | |
result.extend(prefix) | |
result.extend(root) | |
result.extend(suffix) | |
# Sort the result list | |
result.sort(key = len) | |
# Return the result list without duplicate substrings | |
return list(set(result)) | |
if __name__ == '__main__': | |
string = "aabccb" | |
print "String to enumerate:", string | |
print "Substrings:", ', '.join(map(str, enumerate(string))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment