Given
original = 'Has two optional arguments which must be specified.'
and
strings = [{'index': 3, 'string': 'foo'}, {'index': 7, 'string':
'bar'}, {'index': 12, 'string': 'abc'}]
what would be an efficient way (ideally by only iterating once over original) to insert all of the strings in strings to original at their specified index? The function, in this case would return 'Hasfoo twobar optiabconal arguments which must be specified.'.
For example, here is an inefficient implementation I just wrote:
def add_strings(original, strings):
added_length = 0
for i in strings:
insertion_index = i['index'] + added_length
original = original[:insertion_index] + i['string'] +
original[insertion_index:]
added_length += len(i['string'])
return original
originaltoinsertion_indextwice on every iteration was kind of inefficient. It is O(n^2) (I think), which isn't that efficient.index == 3, the first would be added then the second.