moving items in a list

Mark McEahern mark at mceahern.com
Tue Jan 7 16:30:07 EST 2003


Below is some code and unit tests to demonstrate how I'm moving items in a
list.  It works, but I'm sure I'll learn a lot by any feedback you care to
offer.

Cheers,

// m

#!/usr/bin/env python

"""
move 'up' means move the item once towards the first item.

move 'down' means move the item once towards the last item.
"""

import unittest

def move_up(l, m):
    """Move items in m found in l up one position."""
    for i in range(len(l)):
        if i == 0:
            continue
        item = l[i]
        if item not in m:
            continue
        j = i - 1
        swap_with = l[j]
        l[i] = swap_with
        l[j] = item

def move_down(l, m):
    """Move items in m found in l down one position."""
    for i in range(len(l) - 1, 0, -1):
        if i == len(l) - 1:
            continue
        item = l[i]
        if item not in m:
            continue
        j = i + 1
        swap_with = l[j]
        l[i] = swap_with
        l[j] = item

class test(unittest.TestCase):

    def test_move_up(self):
        l = range(10)
        m = [4, 5]
        move_up(l, m)
        expected = [0, 1, 2, 4, 5, 3, 6, 7, 8, 9]
        self.assertEquals(l, expected)

        l = range(10)
        m = [0]
        move_up(l, m)
        expected = range(10)
        self.assertEquals(l, expected)

        l = range(10)
        m = [1, 3, 5, 7, 9]
        move_up(l, m)
        expected = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
        self.assertEquals(l, expected)

    def test_move_down(self):
        l = range(10)
        m = [4, 5]
        move_down(l, m)
        expected = [0, 1, 2, 3, 6, 4, 5, 7, 8, 9]
        self.assertEquals(l, expected)

        l = range(10)
        m = [9]
        move_down(l, m)
        expected = range(10)
        self.assertEquals(l, expected)

        l = range(10)
        m = [1, 3, 5, 7, 9]
        move_down(l, m)
        expected = [0, 2, 1, 4, 3, 6, 5, 8, 7, 9]
        self.assertEquals(l, expected)

if __name__ == '__main__':
    unittest.main()

-






More information about the Python-list mailing list