Inserting while itterating

Mark McEahern mark at mceahern.com
Wed Jan 14 23:19:42 EST 2004


On Wed, 2004-01-14 at 02:43, 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.

In the spirt of unit testing...

#!/usr/bin/env python

import unittest

def fillGaps(seq):
    expectedLength = seq[-1] - seq[0] + 1
    i = 1
    while i < expectedLength:
        if seq[i] - seq[i-1] > 1:
            seq.insert(i, seq[i-1] + 1)
        i += 1

class test(unittest.TestCase):

    def test(self):
        l = [1, 2, 4, 7, 8, 12]
        fillGaps(l)
        self.assertEquals(l, range(1, 13))

unittest.main()






More information about the Python-list mailing list