Inserting while itterating

Thomas Guettler guettli at thomas-guettler.de
Wed Jan 14 06:08:57 EST 2004


Am Wed, 14 Jan 2004 09:43:01 +0100 schrieb Thomas Guettler:

> 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.

No, this is not a homework exerice, 
I was just interested if you have better solutions.
Thank you for your solutions.
Mine looks like this:

l=[1, 2, 4, 7, 8, 12]

i=-1
while 1:
    i+=1
    this=l[i]
    if i+1==len(l):
        # End of list
        break
    next=l[i+1]
    assert(this<next)
    for add in range(this+1, next):
        i+=1
        l.insert(i, add)
print l




More information about the Python-list mailing list