python find repeated substring in string [closed]

柔情痞子 提交于 2021-02-05 03:20:22

问题


I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.

The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.

For example:

"pythonpythonp" => "python"

"hellohello" => "hello"

"appleapl" => "apple"

"spoon" => "spoon"

Can someone give me some hints on how to write this kind of function?


回答1:


You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.

You'll have to try it for every single possible length of string unless you have that saved as a variable

Here's the code:

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:
            print(substring)
            return "break"

    print(string)

repeats("pythonpytho")



回答2:


Start by building a prefix array.

Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1.

Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl' example, where the proposed algorithm would return appl . For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl' you return 'appl' +'e' = 'apple' . If no such strings are found, you return the whole word since there are no repetitions.

def repeat(s):
    prefix_array=[]
    for i in range(len(s)):
        prefix_array.append(s[:i])
    #see what it holds to give you a better picture
    print prefix_array

    #stop at 1st element to avoid checking for the ' ' char
    for i in prefix_array[:1:-1]:
        if s.count(i) > 1 :
            #find where the next repetition starts
            offset = s[len(i):].find(i)

            return s[:len(i)+offset]
            break

    return s


print repeat(s)


来源:https://stackoverflow.com/questions/41077268/python-find-repeated-substring-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!