def get_indices(text, substr): '''Return a list containing the indices where str substr appears in str text. Overlapping instances of substr should be counted. For example, get_indices("abcabcabc", "bc") --> [1, 4, 7] get_indices("bbbbbbb", "bb") --> [0, 1, 2, 3, 4, 5]''' # Accumulate the indices of occurrences here. indices = [] # The position of the next occurrence of substr within text. index = text.find(substr, 0) # Keep looking until there are no more occurrences. while index != -1: # Record this occurrence. indices.append(index) # Advance past this occurrence and look for the next one. index = text.find(substr, index + 1) return indices if __name__ == "__main__": print get_indices("abcabcabc", "bc"), "sb", [1,4,7] print get_indices("bbbbbbb", "bb"), "sb", [0,1,2,3,4,5] print get_indices("bbbbbbb", "aa"), "sb", [] print get_indices("abc", "abcde"), "sb", [] print get_indices("", ""), "sb", [0] print get_indices("abcabcabc", "ab"), "sb", [0,3,6]