SOURCE CODERS

Computer Science and Engineering Study Materials

Study materials for Network Computing


Module 1 (Document)
Module 2 (Document)
Module 3 (Document)
Module 4 (Document)
Module 5 (Document)

Study materials for Software Engineering


Module 1 (Document)
Module 2 (Document)
Module 3 (Document)
Module 4 (Document)
Module 5 (Document)


# Tower of Hanoi problem


def TowerOfHanoi(src, dest, intr, n):
if n > 0:
TowerOfHanoi(src, intr, dest, n-1)
print "Move ", src, " to ", dest
TowerOfHanoi(intr, dest, src, n-1)


n = input("Enter the number of discs : ");
TowerOfHanoi('A', 'B', 'C', n)


# Prims algorithm


from collections import defaultdict
from heapq import *


def prim( nodes, edges ):
    conn = defaultdict( list )
    for n1,n2,c in edges:
        conn[ n1 ].append( (c, n1, n2) )
        conn[ n2 ].append( (c, n2, n1) )


    mst = []
    used = set( nodes[ 0 ] )
    usable_edges = conn[ nodes[0] ][:]
    heapify( usable_edges )


    while usable_edges:
        cost, n1, n2 = heappop( usable_edges )
        if n2 not in used:
            used.add( n2 )
            mst.append( ( n1, n2, cost ) )


            for e in conn[ n2 ]:
                if e[ 2 ] not in used:
                    heappush( usable_edges, e )
    return mst


#test
nodes = list("ABCDEFG")
edges = [ ("A", "B", 7), ("A", "D", 5),
          ("B", "C", 8), ("B", "D", 9), 
 ("B", "E", 7), ("C", "E", 5),
 ("D", "E", 15), ("D", "F", 6),
 ("E", "F", 8), ("E", "G", 9),
 ("F", "G", 11)]


print "prim:", prim( nodes, edges )


#N Queens problem using Backtracking


x = {}
def nqueen(k, n):
for i in range(1, n+1):
if place(k, i):
x[k] = i
if k == n:
print x
else:
nqueen(k+1, n)


def place(row, col):
for j in range(1, row):
if x[j] == col or abs(j-row) == abs(x[j]-col):
return False
return True


n = input("Enter the number of queens : ")
nqueen(1, n)