Wednesday, February 26, 2014

Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

__author__ = 'nitin'

def print_queens():
    print "Result Queen Board:",column_for_row

def place_queen(row):
    if row==8:
        print_queens()
        return True
    for i in range(8):
        column_for_row[row]=i
        if check(row):
            done=place_queen(row+1)
            if done:
                return True

def check(row):
    for i in range(row):
        diff=abs(column_for_row[i] - column_for_row[row])
        if diff ==0 or diff == row -i:
            return False
    return True

if __name__=='__main__':
    column_for_row=[-1]*8
    place_queen(0)

Tuesday, February 25, 2014

Why use Binary Search Trees if we have Linked Lists ?

It mostly depends on scenario. If tail of linked list is maintained then insertion is fast in linked list. Deletion is quite fast in linked list but in case of searching it is better in trees( o(log(n) for height balance tree ) while o(n) in linked list.

A linked list is often unsorted and so addition of new nodes is simply an O(1) operation normally by appending to the tail of the list.

On the other hand a binary tree must store nodes in a specific ordering mechanism (and possibly enforce balancing) to provide for a more efficient searching/retrieval operation.

If your algorithm does NOT need to retrieve items very efficiently while also provide efficient sorting of the items, a linked list is probably all you need.

Queues and Stacks are examples of data structures that can be happily implemented using a linked list.

Note: Insertion to a linked list is a different (slower) operation than basic addition/append. Insertion often requires traversal along the list until the correct position is found, O(n) where n is the list length. An append is simply adding to the tail of the list (hence O(1))

My Profile

My photo
can be reached at 09916017317