def myfun(a, b): """ >>> myfun(2,3) 5 >>> myfun(4,3) 7 """ return a+b if __name__ == '__main__': import doctest doctest.testmod()
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.
Posted by
Abu Zahed Jony
at
1:51 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

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)
Posted by
Abu Zahed Jony
at
1:03 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

Wednesday, April 24, 2013
Bubble sort in python
Bubble sort python code.
Output:
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]
Posted by
Abu Zahed Jony
at
5:10 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

Selection sort in python
Selection sort python code.
Output:
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]
Posted by
Abu Zahed Jony
at
5:06 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

Insertion sort in python
Insertion sort python code.
Output:
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]
Posted by
Abu Zahed Jony
at
5:02 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

Subscribe to:
Posts (Atom)