これを行うには、場所で並べ替えて逆の順序で適用します。同点の場合、順序は重要ですか?次に、場所と順序ではなく、場所のみで並べ替えて、正しい順序で挿入されるようにします。たとえば、999@1を挿入してから888@1を挿入すると、両方の値で並べ替えると888 @ 1,999@1になります。
12345
18889992345
ただし、安定した並べ替えで場所のみを並べ替えると、999 @ 1,888@1になります。
12345
1999888345
コードは次のとおりです。
import random
import operator
# Easier to use a mutable list than an immutable string for insertion.
sequence = list('123456789123456789')
insertions = '999 888 777 666 555 444 333 222 111'.split()
locations = [random.randrange(len(sequence)) for i in xrange(10)]
modifications = zip(locations,insertions)
print modifications
# sort them by location.
# Since Python 2.2, sorts are guaranteed to be stable,
# so if you insert 999 into 1, then 222 into 1, this will keep them
# in the right order
modifications.sort(key=operator.itemgetter(0))
print modifications
# apply in reverse order
for i,seq in reversed(modifications):
print 'insert {} into {}'.format(seq,i)
# Here's where using a mutable list helps
sequence[i:i] = list(seq)
print ''.join(sequence)
結果:
[(11, '999'), (8, '888'), (7, '777'), (15, '666'), (12, '555'), (11, '444'), (0, '333'), (0, '222'), (15, '111')]
[(0, '333'), (0, '222'), (7, '777'), (8, '888'), (11, '999'), (11, '444'), (12, '555'), (15, '666'), (15, '111')]
insert 111 into 15
123456789123456111789
insert 666 into 15
123456789123456666111789
insert 555 into 12
123456789123555456666111789
insert 444 into 11
123456789124443555456666111789
insert 999 into 11
123456789129994443555456666111789
insert 888 into 8
123456788889129994443555456666111789
insert 777 into 7
123456777788889129994443555456666111789
insert 222 into 0
222123456777788889129994443555456666111789
insert 333 into 0
333222123456777788889129994443555456666111789