Skip to content

Instantly share code, notes, and snippets.

@TApicella
Created May 8, 2017 20:09
Show Gist options
  • Save TApicella/c5d97ebeca468d0498c6bcc786a7b9e9 to your computer and use it in GitHub Desktop.
Save TApicella/c5d97ebeca468d0498c6bcc786a7b9e9 to your computer and use it in GitHub Desktop.
RosettaCode Rep-string created by tapicella - https://repl.it/Hmz8/30
'''
rosettacode.org/wiki/Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For example, the string 10011001100 is a rep-string as the leftmost four characters of 1001 are repeated three times and truncated on the right to give the original string.
Note that the requirement for having the repeat occur two or more times means that the repeating unit is never longer than half the length of the input string.
10011 10011
1110 1110 11
001 001 001 0
1010 1010 10
11111 11111
0100101101
010 010 0
101
1 1
0 0
1
'''
def isRep(s):
rep = False
pattern = None
print("Testing string \'%s\'" % s)
for i in range(1, (len(s)//2)+1):
#First, see if there is a pattern at all.
first = s[0:i]
second = s[i:2*i]
#print(first+" "+second)
if first == second:
#print("Pattern %s found" % first)
rep = True
pattern = first
#if you want all patterns besides the longest, make an array of patterns
#Next, see how many times the pattern repeats, and if it goes to the end
if rep:
test = s
n = 0
while len(test) >= len(pattern):
if test[0:len(pattern)] == pattern:
n+=1
test = test[len(pattern):]
else:
print("Not a rep-string")
return
print("Pattern is %s, number of repetitions is %d" % (pattern, n))
else:
print("Not a rep-string")
isRep('1001110011')
isRep('1110111011')
isRep('0010010010')
isRep('1010101010')
isRep('1111111111')
isRep('0100101101')
isRep('0100100')
isRep('101')
isRep('11')
isRep('00')
isRep('1')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment