How can I tell if a string repeats itself in Python?

后端 未结 13 1418
栀梦
栀梦 2020-11-27 09:07

I\'m looking for a way to test whether or not a given string repeats itself for the entire string or not.

Examples:

[
    \'0045662100456621004566210         


        
13条回答
  •  失恋的感觉
    2020-11-27 09:30

    First, halve the string as long as it's a "2 part" duplicate. This reduces the search space if there are an even number of repeats. Then, working forwards to find the smallest repeating string, check if splitting the full string by increasingly larger sub-string results in only empty values. Only sub-strings up to length // 2 need to be tested since anything over that would have no repeats.

    def shortest_repeat(orig_value):
        if not orig_value:
            return None
    
        value = orig_value
    
        while True:
            len_half = len(value) // 2
            first_half = value[:len_half]
    
            if first_half != value[len_half:]:
                break
    
            value = first_half
    
        len_value = len(value)
        split = value.split
    
        for i in (i for i in range(1, len_value // 2) if len_value % i == 0):
            if not any(split(value[:i])):
                return value[:i]
    
        return value if value != orig_value else None
    

    This returns the shortest match or None if there is no match.

提交回复
热议问题