Python Tutorial

Tuesday, December 4, 2012

Django-piston REST API


REST API using django and django-piston.
Piston lets you develop API for your site. From my experience in piston you can write API very fast. Lets have a small drive ...
A sample API code with readme available on github.

Monday, December 3, 2012

DFS Algorithm in Python


Depth-first search (DFS) is very usefull for traversing or searching a tree, tree structure, or graph. Here python implementation of DFS .
All source code available on github

 # DA_DFS.py
class DFS:
    def __init__(self, node,edges):
        self.node = node
        self.edges = edges
        self.color=['W' for i in range(0,node)] # W for White
        self.graph =color=[[False for i in range(0,node)] for j in range(0,node)]
        self.parent =[-1 for u in range(0,node)]

        # Start DFS
        self.construct_graph()
        self.dfs_traversal()

    def construct_graph(self):
        for u,v in self.edges:
            self.graph[u][v], self.graph[v][u] = True, True

    def dfs_visit(self, u):
        self.color[u]='G' # G for Gray
        for i in range(0, self.node):
            if self.graph[u][i]==True and self.color[i]=='W':
                self.parent[i]=u
                self.dfs_visit(i)
        self.color[u]='B' # B for black

    def dfs_traversal(self):
        for i in range(0,self.node):
            if self.color[i]=='W': # W for white
                self.dfs_visit(i)

    def print_path(self, source, destination):
        if destination==source:
            print destination,
        elif self.parent[destination] == -1:
            print "No Path"
        else:
            self.print_path(source, self.parent[destination])
            print "-> ",destination,

node = 8 # 8 nodes from 0 to 7
edges =[(0,1),(0,3),(1,2),(1,5),(2,7),(3,4),(3,6),(4,5),(5,7)] # bi-directional edge

dfs = DFS(node, edges)
dfs.print_path(0, 7)
print ""
dfs.print_path(2, 5)
print ""
dfs.print_path(0, 4)


Output:
0 ->  1 ->  2 ->  7 
2 ->  7 ->  5 
0 ->  1 ->  2 ->  7 ->  5 ->  4

BFS Algorithm in Python


Breadth-first search(BFS) is one of the most widely used graph algorithm for single source shortest path. Here I shown python implemenation of this beautiful algorithm.
All source code available on github

#DA_BFS.py
from collections import deque

class BFS:
    def __init__(self, node,edges, source):
        self.node = node
        self.edges = edges
        self.source = source
        self.color=['W' for i in range(0,node)] # W for White
        self.graph =color=[[False for i in range(0,node)] for j in range(0,node)]
        self.queue = deque()
        self.parent =[-1 for u in range(0,node)]

        # Start BFS algorithm
        self.construct_graph()
        self.bfs_traversal()

    def construct_graph(self):
        for u,v in self.edges:
            self.graph[u][v], self.graph[v][u] = True, True

    def bfs_traversal(self):

        self.queue.append(self.source)
        self.color[self.source] = 'B' # B for Black

        while len(self.queue):
            u =  self.queue.popleft()
            for v in range(0,self.node):
                if self.graph[u][v] == True and self.color[v]=='W':
                    self.color[v]='B'
                    self.queue.append(v)
                    self.parent[v]=u

    def print_shortest_path(self, destination):
        if destination==self.source:
            print destination,
        elif self.parent[destination] == -1:
            print "No Path"
        else:
            self.print_shortest_path(self.parent[destination])
            print "-> ",destination,



node = 8 # 8 nodes from 0 to 7
edges =[(0,1),(0,3),(1,2),(1,5),(2,7),(3,4),(3,6),(4,5),(5,7)] # bi-directional edge
source = 0 # set fist node (0) as source

bfs = BFS(node,edges,source)
bfs.print_shortest_path(5) # shortest path from 0 to 5
print
bfs.print_shortest_path(7) # shortest path from 0 to 7


Output:
0 ->  1 ->  5
0 ->  1 ->  2 ->  7

python dequeue data structure


Double-ended queue(dequeue) in python.
All source code available on github

#DA_Dequeue.py

from collections import deque

myDequeue = deque()

myDequeue.append(5) # insert element at back
myDequeue.appendleft(9) # insert element at front
myDequeue.append(55)
myDequeue.appendleft(99)
print myDequeue

print myDequeue.pop() # remove last element
print myDequeue
print myDequeue.popleft() # remove first element
print myDequeue
print myDequeue[-1] # last element
print myDequeue[0] # fist element



Output:
deque([99, 9, 5, 55])
55
deque([99, 9, 5])
99
deque([9, 5])
5
9

Friday, November 23, 2012

Design pattern in python : Factory method


Factory method pattern in python.
All source code available on github

class Book:
    def book_category(self):    pass

class PythonBook(Book):
    def book_category(self):
        print "Python book"

class JavaBook(Book):
    def book_category(self):
        print "Java book"

class BookFactory:
    def get_book(self, book_type):
        if book_type=='python':
            return PythonBook()
        elif book_type=='java':
            return JavaBook()
        else:
            return None

bookFactory = BookFactory()
pythonBook = bookFactory.get_book('python')
pythonBook.book_category()

javaBook = bookFactory.get_book('java')
javaBook.book_category()



Output:
Python book
Java book

Design pattern in python: Template method


Template method design pattern in python.
All source code available on github

class MakeMeal:

    def prepare(self):  pass
    def cook(self): pass
    def eat(self):  pass

    def go(self):
        self.prepare()
        self.cook()
        self.eat()

class MakePizza(MakeMeal):

    def prepare(self):
        print "Prepare Pizza"

    def cook(self):
        print "Cook Pizza"

    def eat(self):
        print "Eat Pizza"

class MakeTea(MakeMeal):

    def prepare(self):
        print "Prepare Tea"

    def cook(self):
        print "Cook Tea"

    def eat(self):
        print "Eat Tea"

makePizza = MakePizza()
makePizza.go()

print 25*"+"

makeTea = MakeTea()
makeTea.go()



Output:
Prepare Pizza
Cook Pizza
Eat Pizza
+++++++++++++++++++++++++
Prepare Tea
Cook Tea
Eat Tea

hashlib : secure hashes and message digests


hashlib implements many different secure hash and message digest algorithms(SHA1, SHA224, SHA256, SHA384, SHA512, MD5). Lets have a look...

 
import hashlib

message = "python"

print "md5"
print hashlib.md5(message).hexdigest()

print "sha1"
print hashlib.sha1(message).hexdigest()

print "sha512"
print hashlib.sha512(message).hexdigest()

print "sha224"
print hashlib.sha224(message).hexdigest()

print "sha256"
print hashlib.sha256(message).hexdigest()

print "sha384"
print hashlib.sha384(message).hexdigest()



Output:
md5
23eeeb4347bdd26bfc6b7ee9a3b755dd
sha1
4235227b51436ad86d07c7cf5d69bda2644984de
sha512
ecc579811643b170cbd88fd0d0e323d1e1acc7cef8f73483a70abea01a89afa8015295f617f27447ba05e928e47a0b3a46dc79e72f99d1333856e23eeff97d8b
sha224
dace1c32d56e6f2bd077266a5a381fcf7ff9052e0a269e32cd52a551
sha256
11a4a60b518bf24989d481468076e5d5982884626aed9faeb35b8576fcd223e1
sha384
2690f7fce3051903a4e8b9f1f9ea705f070f03f9d84c353f2653cece80ea68130ef8defd53ef29af5f236e6cac7c7efb