Skip to main content
added 1 character in body
Source Link
Aguy
  • 213
  • 2
  • 9

@200_success solution is great. In case you still want to make the comparison in nested looploops I think it is cleaner to have it all in one simple function. The following is just such nested loops function. The hardest part is formulating the indices correctly.

def brokenrecord(sentence):
    words = sentence.split(' ')
    n = len(words)
    for i in range(n):
        for j in range(int((n-i)/2)):
            if words[i:i+j+1] == words[i+j+1:i+2*j+2]:
                return True
    return False

@200_success solution is great. In case you still want to make the comparison in nested loop I think it is cleaner to have it all in one simple function. The following is just such nested loops function. The hardest part is formulating the indices correctly.

def brokenrecord(sentence):
    words = sentence.split(' ')
    n = len(words)
    for i in range(n):
        for j in range(int((n-i)/2)):
            if words[i:i+j+1] == words[i+j+1:i+2*j+2]:
                return True
    return False

@200_success solution is great. In case you still want to make the comparison in nested loops I think it is cleaner to have it all in one simple function. The following is just such nested loops function. The hardest part is formulating the indices correctly.

def brokenrecord(sentence):
    words = sentence.split(' ')
    n = len(words)
    for i in range(n):
        for j in range(int((n-i)/2)):
            if words[i:i+j+1] == words[i+j+1:i+2*j+2]:
                return True
    return False
Source Link
Aguy
  • 213
  • 2
  • 9

@200_success solution is great. In case you still want to make the comparison in nested loop I think it is cleaner to have it all in one simple function. The following is just such nested loops function. The hardest part is formulating the indices correctly.

def brokenrecord(sentence):
    words = sentence.split(' ')
    n = len(words)
    for i in range(n):
        for j in range(int((n-i)/2)):
            if words[i:i+j+1] == words[i+j+1:i+2*j+2]:
                return True
    return False