This is my first Python program in years, it's just a simple string manipulation program. Given a string, determine if it contains repetitions of any substring. For example, testtest
contains two substring test
and nothing else.
def onlySubstrings(stringOrig):
stringCopy = (stringOrig+'.')[:-1] # copy string contents
for i in range(1, len(stringCopy)): # for each character
stringCopy = stringCopy[1:]+stringCopy[0] # shift first char to end
if stringCopy == stringOrig: # if equivalent to original input
return True # it consists of substrings only
else: # otherwise the only substring is the string itself
return False
if __name__ == '__main__':
wordList = ['testtest','testteste','test','tetestst'] # some test words
print('The below words only contain substring repetitions:')
for word in wordList: # for each word
print(onlySubstrings(word), '\t', word)
If you imagine the string as circular unto itself, the string can only contain equal substring(s) if you can move the characters to the left or right and get the same original string in less than len
shifts:
testtest - 0 shifts, original string
esttestt - 1 shift, not original
sttestte - 2 shifts, not original
ttesttes - 3 shifts, not original
testtest - 4 shifts, original again
Since 4 < len
, it contains only substring repetitions.
testteste - 0 shifts, original string
esttestet - 1 shift, not original
...
etesttest - (len-1) shifts, not original
testteste - len shifts, original again
Since we couldn't find the original string again in under len
shifts, it does not only contain repetitions of a substring.
len-1
times, rather I need to shiftceil(len/2)
times. Saves a little time. \$\endgroup\$i
does not evenly dividelen(str)
since doing so would attempt to match partials which we know won't be true \$\endgroup\$