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]