위치를 정렬하고 역순으로 적용하면됩니다. 동점의 경우에 순서가 중요합니까? 그런 다음 위치 및 순서가 아닌 위치별로 정렬해야 올바른 순서로 삽입됩니다. 예를 들어, 999 @ 1 다음에 888 @ 1을 삽입하는 경우 두 값을 모두 정렬하면 888 @ 1,999 @ 1이됩니다.
12345
18889992345
하지만 안정된 종류와 위치에 따라 분류하는 것은 999 일
12345
1999888345
@ 1888 @ 여기에 코드입니다 제공 :
이
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
결정하여 삽입 점을 임의로 먼저 정렬하고 정렬 한 다음 삽입합니다. 뒤에서 앞으로. – mVChr