Inserting while itterating

anton muhin antonmuhin at rambler.ru
Wed Jan 14 11:46:48 CET 2004


Thomas Guettler wrote:

> Hi,
> 
> Simple excerise:
> 
> You have a sorted list of integers:
> l=[1, 2, 4, 7, 8, 12]
> 
> and you should fill all gaps:
> 
> result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> 
> How would you code this?
> 
> Constrain: The original list should be changed,
> don't create a copy.
> 
>   thomas
> 

1:

previous = l[0]
current = 1

while current < len(l):
     for e in range(previous + 1, l[current]):
         l.insert(current, e)
         current += 1
     previous = l[current]
     current += 1


2:

first, last = l[0], l[-1]
for _ in range(len(l)): l.pop()
l.extend(range(first, last + 1))

:)

hth,
anton.



More information about the Python-list mailing list