Skip to content

Instantly share code, notes, and snippets.

@nboubakr
Created March 21, 2013 21:38
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 nboubakr/5217045 to your computer and use it in GitHub Desktop.
Save nboubakr/5217045 to your computer and use it in GitHub Desktop.
Enumerate a string to substrings
#!/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