Wednesday, November 3, 2010

Learning Python

My project for SBR600 is fedpkg Test Suite. For 0.1 release, I plan to write some simple functions in manipulating list, and then use nose to test the functions. The first function I try to write is a simple exercise: given a list of numbers, the function will remove the negative items.

The first try

def rem_neg(list):
    for i in list:
        if list[i] < 0:
            list.remove(list[i])

before I use nose to test, I did some regular test. Give a list [1, 2, -1, 3, -2], the result will be [1,2,3]. Not bad. But when I use [5,-1,-2,3,4,-8], the result is [5-2,3,4]. So the function is not right. I went to check the book and realized that when a list remove an item, the rest will shift to the left. Therefore, the for loop missing the second negative number if two negative numbers next to each other.

The second try

I tried to find a way to work around the shifting problem. How about do the loop backward? Then the shift won't cause problem anymore.

def rem_neg(list)
    for i in range(len(list)-1, 0, -1):
        if list[i] < 0:
            list.remove(list[i])

I tested the previous example. It worked. But I should test more examples. The text book I am read said to use special case or extreme case to test. When I test list [-1], it failed again. The result is [-1]. So the function didn't reach the first item (It's the last if we consider the loop goes backward). It's typical "off by 1" error in programming. My for loop range should be (len(list)-1, -1, -1). The range function always stop 1 before the last item.

Come to nose

Now I put the function to nose test.

import nose

def rem_neg(list)
    for i in range(len(list)-1, -1, -1):
        if list[i] < 0:
            list.remove(list[i])
def test_rem_neg():
    assert rem_neg([-1]) == []

if __name__ == '__main__' :
    nose.runmodule()

The test failed. It took a while for me to figure out what is wrong. The function rem_neg(list) return none. I wrote the function this way just to follow the style of list built-in functions. This is: the original list get modified and nothing returned (except the pop function).

Come next: 0.1 release

This is just the first example I plan to use for the nose test. I will test more examples in two days and finish my 0.1 release.

No comments:

Post a Comment