Python Tutorial

Thursday, April 25, 2013

Doctest in python

The doctest module searches for pieces of text that look like interactive Python sessions in docstrings, and then executes those sessions to verify that they work exactly as shown. If test failed it will shows proper message.

def myfun(a, b):
    """
    >>> myfun(2,3)
    5
    >>> myfun(4,3)
    7
    """
    return a+b


if __name__ == '__main__':
    import doctest
    doctest.testmod()

Python unittest

Unittest is included in the Python standard library. It is very easy to use. Here I write two function named myfun, reverse and then unsing MyTest function I tested those two functions. Let's check.

import unittest

def myfun(a, b):
    return a+b

def reverse(A):
    i = 0
    j = len(A)-1
    while i<j:
        A[i], A[j] = A[j], A[i]
        i = i + 1
        j = j -1

class MyTest(unittest.TestCase):
    def test(self):
        self.assertEqual(myfun(2, 3), 5)
        self.assertEqual(myfun(4, 3), 7)

        # test reverse(A)
        A = [1, 2, 3]
        expected = [3, 2, 1]
        reverse(A)
        self.assertEqual(A, expected)
        

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

Wednesday, April 24, 2013

Bubble sort in python

Bubble sort python code.

def bubble_sort(A):
    n = len(A)    
    for i in range(0,n):
        for j in range (i+1,n):
            if A[i]>A[j]:
                A[i],A[j]=A[j], A[i]

if __name__=="__main__":
    A = [7,3,5,2]
    print A
    bubble_sort(A)
    print A

Output:
[7, 3, 5, 2]
[2, 3, 5, 7]

Selection sort in python

Selection sort python code.

def get_index_of_smallest(A, i):
    index_of_smallest = i
    for j in range(i+1, len(A)):
        if A[index_of_smallest]>A[j]:
            index_of_smallest = j;
    return index_of_smallest


def selection_sort(A):
    for i in range (0, len(A)):
        index_of_smallest = get_index_of_smallest(A,i)
        A[index_of_smallest], A[i] = A[i], A[index_of_smallest]

if __name__=="__main__":
    A = [7,3,5,2]
    print A
    selection_sort(A)
    print A

Output:
[7, 3, 5, 2]
[2, 3, 5, 7]

Insertion sort in python

Insertion sort python code.


def insert(A,i):
    value = A[i]
    j = i
    while j != 0 and A[j-1]>value:
        A[j] = A[j-1]
        j = j - 1
    A[j] = value


def insertion_sort(A):
     for i in range(len(A)):
         insert(A, i)

if __name__=="__main__":
    A = [7,3,5,2]
    print A
    insertion_sort(A)
    print A


Output:
[7, 3, 5, 2]
[2, 3, 5, 7]