Wednesday, May 5, 2010

Some Python tips & tricks

Long time since my last post,i'm kinda busy with my last term as an undergrad. Anyway i'll reward you with some posts (hope so) starting with this one.
Last summer i learned python as you may know from a previous post. And this semester i used it in the Pattern Recognition course projects. I know Matlab is best suitable for them but i had no time to learn Matlab.
During the projects i learned so many useful things about python and some few tips and tricks that help writing better code. So here you are some of them ..

1- Follow Google styleguide for python http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

2- sorting a dictionary
unsorteddic = {'a':5,'b':4,'c':3,'d':2,'e':1}
result = sorted(unsorteddic.items(),lambda x,y: cmp(x[1],y[1]))

3- dividing a list into equal sized sub lists using lambda functions. Lambda functions are very powerful tools to use in your code.
#A:list to split, size: size of each sublist
splitter = lambda A,size: [A[i:i+size]for i in range (0,len(A),size)]

#in the main code, we want to divide data into 3 sub sets
data = [(1,2),(3,4),(5,6),(7,8),(9,10),(11,12),(13,14),(15,16),(17,18)]
triplet = len(data)/3
sublist1,sublist2,sublist3 = splitter(data,triplet)

4- using zip function to separate/combine pairs in a list, like x,y coordinates of points.
XY = [(1,2),(3,4),(5,6),(7,8),(9,10),(11,12),(13,14),(15,16),(17,18)]
#separating them
X,Y = zip(*XY)
#combining results again
recombined = zip(X,Y)

5- using list comprehension to optimize your code and save time. For this example it's better to use the last zip function (follow the Zen of Python)
XY = [(1,2),(3,4),(5,6),(7,8),(9,10),(11,12),(13,14),(15,16),(17,18)]
#implementing our zip function
X,Y = [XY[i][0] for i in range(0,len(XY))],[XY[i][1] for i in range(0,len(XY))]
#recombining again
recombined = [tuple(X[i],Y[i]) for i in range(0,len(X))]

That's most of the things i used in my projects. Ofcourse there are more but still i am a beginner. If you have any suggestion to the above code you are sure welcomed.
Python in peace

No comments:

Post a Comment