Python Tutorial

Tuesday, September 30, 2014

Python profiling

Profiling in python is very handy. It will help you to monitor your code performance and find the hot spot of your code.
Here I am using cProfile for profiling. It is built in with python.

Download sample code , unzip the file and cd to the folder.
No run this command python -m cProfile a.py
Output will be

Visualization of cProfile data:

I used RunSnakeRun for visualization.
Now run this following two command (make sure you installed RunSnakeRun)
python -m cProfile -o file.prof a.py
runsnake file.prof

Output will be

Check it out.

Sunday, September 28, 2014

Min, max value and index from list

See also enumerate and operator.itemgetter
import operator
a = [2, 5, 1, 4, 8, 71, 4, 1, 21]
min_i, min_v = min(enumerate(a), key = operator.itemgetter(1))
max_i, max_v = max(enumerate(a), key = operator.itemgetter(1))

print "[Min] index:",min_i,"value:",min_v
print "[Max] index:",max_i,"value:",max_v


Output:
[Min] index: 2 value: 1
[Max] index: 5 value: 71

Python: Absolute difference between successive elements in list


See also abs, zip and islice
from itertools import islice

a = [1, 4 , 2 , 6 , 7, 3]
result = [abs(p-q) for p, q in zip(a, islice(a, 1, None))]

print result

Output:
[3, 2, 4, 1, 4]

Wednesday, June 4, 2014

Python multi threading vs multi processing



A very good article on python multi threading vs multi processing

Python Requests: HTTP for Humans


Python requests module provides very interactive way to access web content via proper HTTP protocol.

Installation:
Here is the installation manual. You can also install using pip :
pip install requests

import requests

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
print r.json()

Output:
200
'application/json; charset=utf8'
'utf-8'
u'{"type":"User"...'
{u'private_gists': 419, u'total_private_repos': 77, ...}


Python webbrowser


Python webrowser provides high-level interface to displaying Web-based documents.
import webbrowser

url ='https://docs.python.org'
webbrowser.open(url, new=0, autoraise=True)


Output:

This code will open url to existing web browser and raised the window.

Saturday, May 10, 2014

Python unittest examle



All source code available on github
Python unittest example. Here I am testing my insertion sort code.
import random
import unittest


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)

class TestInsertionSort(unittest.TestCase):

    def setUp(self):
        print "Setup ..."

    def testSortRange(self):
        print "TestSortRange .... \n"
        n = 10
        a = range(n)
        random.shuffle(a)
        insertion_sort(a)
        self.assertEqual(a, range(n))

        n = 1
        a = range(n)
        random.shuffle(a)
        insertion_sort(a)
        self.assertEqual(a, range(n))

        n = 77
        a = range(n)
        random.shuffle(a)
        insertion_sort(a)
        self.assertEqual(a, range(n))

    def testSortData(self):
        print "TestSortData .... \n"
        a = []
        r = []
        insertion_sort(a)
        self.assertEqual(a, r)

        a = [3, 1, 2]
        r = [1, 2, 3]
        insertion_sort(a)
        self.assertEqual(a, r)


if __name__=="__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestInsertionSort)
    unittest.TextTestRunner(verbosity=2).run(suite)


Output:
testSortData (__main__.TestInsertionSortSetup ..) ... ok
.
TestSortData .... 

Setup ...
TestSortRange .... 

testSortRange (__main__.TestInsertionSort) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
[Finished in 0.1s]