Saturday, January 18, 2014

Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

#!/usr/bin/python

a=[[1,2,3],[4,5,6],[7,0,0],[10,9,12]]
#a=[[10,7,4,1],[17,0,5,2],[12,9,6,3]]
num_of_rows=len(a)
num_of_col=len(a[0])

#### Using dictionary here but it is a bug because dict replacing the value if same key found :-)
def matrix_wd_zero():
    m_dict={}
    print "Given Matrix : ", a
    for i in range(num_of_rows):
        for j in range(num_of_col):
            m_value=a[i][j]
            if m_value == 0:
                m_dict[i]=j
    for i,j in m_dict.items():
        for k in range(num_of_col):
            a[i][k]=0
        for p in range(num_of_rows):
            a[p][j]=0
    print "Result Matrix : ", a


############ Efficient and correct Function
def matrix_wd_zero2():
    print "Given Matrix : ", a
    for i in range(num_of_rows):
        for j in range(num_of_col):
            if a[i][j]==0:
                for k in range(num_of_col):
                    a[i][k]=100
                for p in range(num_of_rows):
                    a[p][j]=100
    for i in range(num_of_rows):
        for j in range(num_of_col):
            if a[i][j]==100:
                a[i][j]=0
    print "Result Matrix : ", a

if __name__=='__main__':
    #matrix_wd_zero()
    matrix_wd_zero2()

Thursday, January 9, 2014

Linked List in Python

############################## Start of the Program

#!/usr/bin/python

class Node:
    def __init__(self,initdata):
        self.data=initdata
        self.next=None
    def getData(self):
        return self.data
    def setData(self,item):
        self.data=item
    def getNext(self):
        return self.next
    def setNext(self,item):
        self.next=item

class UnorderedList:
    def __init__(self):
        self.head=None

    def isEmpty(self):
        return self.head==None

    def add(self,item):
        temp=Node(item)
        temp.setNext(self.head)
        self.head=temp

    def size(self):
        current=self.head
        count=0
        while current!=None:
            count=count+1
            current=current.getNext()
        return count

    def search(self,item):
        current=self.head
        found=False
        while current!=None and not found:
            if current.getData()==item:
                found=True
            else:
                current=current.getNext()
        return found

    def remove(self,item):
        current=self.head
        prev=None
        found=False
        while current!=None and not found:
            if current.getData()==item:
                found=True
            else:
                prev=current
                current=current.getNext()
        if prev==None:
            self.head=current.getNext()
        else:
            prev.setNext(current.getNext())

########################### End of the Program

My Profile

My photo
can be reached at 09916017317