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

Wednesday, January 8, 2014

Program to check anagram strings with O(n)

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

#!/usr/bin/python

first_str=raw_input("Please input first string: ")
second_str=raw_input("Please input second string: ")

def validate_anagram():
    c1=[0]*26
    c2=[0]*26
    len_iter1=len(first_str)
    len_iter2=len(second_str)
    while len_iter1>0:
        char_of_str=first_str[len_iter1 - 1]
        pos=ord(char_of_str) - ord('a')
        c1[pos]=c1[pos] + 1
        len_iter1=len_iter1 - 1
    while len_iter2>0:
        char_of_str=second_str[len_iter2 - 1]
        pos=ord(char_of_str) - ord('a')
        c2[pos]=c2[pos] + 1
        len_iter2=len_iter2 - 1
    len_iter3=len(c1)
    while len_iter3>0:
        num_of_list=len_iter3 - 1
        if c1[num_of_list] == c2[num_of_list]:
            pass
        else:
            print "Given strings are not anagrams"
            break
        len_iter3=len_iter3 - 1

if __name__=='__main__':
    validate_anagram()

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

My Profile

My photo
can be reached at 09916017317