[Python] Enumerate a string to substrings

Today I’d like to show you a quick hint that might be obvious, but it took useful, it’s about the enumeration of string to substrings.


You probably know the deffinition of a substring, so Y is a substring for X if: X = U.Y.V

#!/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)))

Enjoy !

Tagged: , , , , ,

Leave a Reply :

This site uses Akismet to reduce spam. Learn how your comment data is processed.