Small String that continuously repeated in Big String

Viewed 37

I am trying to get a length of a Small string that repeats large string continuously in Python

I Tried...

def repeats(string):
for x in range(1, len(string)):
    substring = string[:x]

    if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
        return "break"

print(len(substring))

But it's long.. Plese Give me your knowledge.

1 Answers

You might be able to use a regex re.findall approach here:

def longest_repeat(x):
    matches = re.findall(r'(.+)\1+', x)
    matches.sort(key=lambda s: len(s), reverse=True)
    if not matches:
        return ''
    else:
        return matches[0]

inp = ["agtcaggtccaggtccgatcgaatac", "agtcgggggggatta", "agtctgcatgac"]
for i in inp:
    output = longest_repeat(i)
    print(i + ', ' + output)

This prints:

agtcaggtccaggtccgatcgaatac, caggtc
agtcgggggggatta, ggg
agtctgcatgac, 
Related