I was asked to complete a coding challenge for an interview. The challenge being to write a test function to check whether or not a string was a
broken record. A
broken record is defined as a string that contains a sequential repeated substrings. For example:
# These are broken records "This is is a broken record" "This is a is a broken record" "This is a broken record. This is a broken record." # These are not broken records "This is not is a broken record" "This is a is This" "This is a broken record. This is not a broken record."
This is the code that I was able to come up with (Python 2.7). Any criticisms, improvements, or suggestions are greatly appreciated.
# Author: Jeremiah Zucker # brokenRecord.py # A small module to test whether a substring is repeated # immediately, like a broken record def brokenRecord(sent): if sent == "": # Use defualt string if empty sent = "This is a a is This" print("Determining if broken record: %s" % sent) arr = sent.split(" ") # Create count array for the sentence carr =  * len(arr) for i in range(0,len(arr)): carr[i] = arr.count(arr[i]) # For each element in the array, try to find the # repeat if one is possible for i in range(0,len(arr)): if carr[i] > 1 and findRepeat(arr, i): print("Is a broken record at %d!" % i) return print("Not a broken record.") def findRepeat(arr, i): beg = arr[i] j = i # Find all other indices of 'beg' others =  while beg in arr[j+1:]: j = arr[j+1:].index(beg) + j + 1 others.append(j) # For all other indices of 'beg' for j in others: # Get both substrings lenRep = j - i try: rep = arr[i:j] rep2 = arr[j:j+lenRep] except IndexError: continue # Are they equal? if rep == rep2: # print(rep) # print(rep2) return True # Nope return False if __name__ == '__main__': # print usage print("brokenRecord.py") print("To use, type a string and hit ENTER.") print("If no string is provided, the default string will be used.") # do until ctrl+c while True: try: brokenRecord(raw_input("\nString: ")) except KeyboardInterrupt: print("\nThanks for testing!") break