2016-07-27 4 views
3

일부 문자열의 복사본이 하나 이상있는 문자열이 있습니다. 예를 들면 다음과 같습니다.문자열을 반복 된 부분 문자열로 분할하는 방법

이러한 문자열을 목록으로 분할하여 각 요소에 반복되는 부분이 있도록하고 싶습니다. 예를 들면 다음과 같습니다.

splitstring(L) ---> ["hello", "hello", "hello"] 
splitstring(M) ---> ["good"] 
splitstring(N) ---> ["where", "where"] 
splitstring(O) ---> ["ant", "ant"] 

문자열의 길이가 약 1000 자이기 때문에 합리적으로 빠릅니다.

필자의 경우 반복은 모두 문자열의 시작에서 시작하여 그 사이에 간격이 없으므로 문자열에서 최대 반복을 찾는 일반적인 문제보다 훨씬 간단합니다.

어떻게하면됩니까?

+0

이 [질문] 한 번 봐 (http://stackoverflow.com/questions/11090289/find-longest-repetitive-sequence-i을 n-a-string) 나는 당신이 비슷한 것을 찾고 있다고 생각하니? 또한이 방법의 복잡도는 O (n)이므로 요구 사항에 따라 매우 빠릅니다. –

+0

@MridulKashyap 제 질문은 훨씬 간단합니다. 반복은 문자열의 시작 부분에서 시작하고 그 사이에 간격이 없습니다. – eleanora

답변

4

단순히 적절한 길이의 목록 작성, 반복되는 단어를 찾는 정규 표현식을 사용하여이 작업 할

def splitstring(string): 
    match= re.match(r'(.*?)(?:\1)*$', string) 
    word= match.group(1) 
    return [word] * (len(string)//len(word)) 
+0

좋은 생각, 나는 그와 비슷한 것을하려고 생각했다. – alex

0

접근 제가 사용한다 :

import re 

L = "hellohellohello" 
N = "good" 
N = "wherewhere" 

cnt = 0 
result = '' 
for i in range(1,len(L)+1): 
    if cnt <= len(re.findall(L[0:i],L)): 
     cnt = len(re.findall(L[0:i],L)) 
     result = re.findall(L[0:i],L)[0] 

print(result) 

는 대응 변수 다음 출력을 제공합니다

hello 
good 
where 
1

이것을 시도. 목록을 자르지 않고 가장 짧은 패턴을 찾은 다음이 패턴을 적절한 횟수만큼 반복하여 새 목록을 만듭니다.

def splitstring(s): 
    # searching the number of characters to split on 
    proposed_pattern = s[0] 
    for i, c in enumerate(s[1:], 1): 
     if proposed_pattern == s[i:(i+len(proposed_pattern))]: 
      # found it 
      break 
     else: 
      proposed_pattern += c 
    else: 
     print 'found no pattern' 
     exit(1) 
    # generating the list 
    n = len(proposed_pattern) 
    return [proposed_pattern]*(len(s)//n) 


if __name__ == '__main__': 
    L = 'hellohellohellohello' 
    print splitstring(L) # prints ['hello', 'hello', 'hello', 'hello'] 
+0

나는이 3 가지를 몰랐다. 고마워요. 나는 이것을 시험해보고 – BusyAnt

0

반복되는 단어의 길이가 1 이상이라고 가정을 :

a = "hellohellohello" 

def splitstring(string): 
    for number in range(1, len(string)): 
     if string[:number] == string[number:number+number]: 
      return string[:number] 
    #in case there is no repetition 
    return string 

splitstring(a) 
+2

"aabaab"에서 실패합니다. – cogitovita

0
#_*_ coding:utf-8 _*_ 
import re 
''' 
refer to the code of Gábor Erds below 
''' 

N = "wherewhere" 
cnt = 0 
result = '' 
countN = 0 
showresult = [] 

for i in range(1,len(N)+1): 
    if cnt <= len(re.findall(N[0:i],N)): 
     cnt = len(re.findall(N[0:i],N)) 
     result = re.findall(N[0:i],N)[0] 
     countN = len(N)/len(result) 
for i in range(0,countN): 
    showresult.append(result) 
print showresult 
+0

코드가 [Gábor Erdős의 게시물] (http://stackoverflow.com/a/38608219/5488275)과 다른 이유에 대한 설명을 추가하십시오. –

관련 문제