Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Saturday, May 4, 2019

Filter Cryillic file from the folder in python


Saturday, June 2, 2018

Inserting of elements in Binary search tree with minimal tree creation in Python

class node:
    def __init__(self,val):
        self.value = val
        self.left = None        self.right = None
def insert_node(val,root):
    if(val<root.value):
        if(root.left is None):
            root.left = node(val)
        else:
            insert_node(val,root.left)

    else:
        if(root.right is None):
            root.right = node(val)
        else:
            insert_node(val,root.right)

def inorder(root):
    if(root):
        print(root.value)
        inorder(root.left)
        inorder(root.right)

def minimal_tree(arr,start,end):
    if(start>end):
        return None    mid = (start+end)//2    root = node(arr[mid])
    root.left = minimal_tree(arr,start,mid-1)
    root.right = minimal_tree(arr,mid+1,end)

    return root

root = node(3)

x= [5,4,1,2]
for i in x:
    insert_node(i,root)

inorder(root)
y = [1, 2, 3, 4, 5 ,6 ,7, 8,9]




test = minimal_tree(y,0,len(y)-1)
print(test.value)
inorder(test)

Tuesday, May 29, 2018

recursive and iterative BFS, DFS,inorder traversal of graph in python

from collections import defaultdict
import queue

#######DFS  RECURSIVE
class node:
    def __init__(self,value):
        self.data = value
        self.left = None        
        self.right  = None
class DFS:
    def __init__(self):
        self.graph =defaultdict(list)
    def dfs_call(self,visited,val):
        if val is None:
            return        
        visited[val] = True        
        print(val)

        for i in self.graph[val]:
            if i is not None:
                if(visited[i]==False):
                    self.dfs_call(visited,i)


    def dfs_recursive(self,val):
        visited = [False]*(len(self.graph))
        self.dfs_call(visited, val)

###### DFS RECURSIVE

#######DFS ITERATIVE for binary tree
def dfs_iter(root):
    visited = [False]*10    
    stack =[]
    stack.append(root)

    while(stack):
        val = stack.pop()
        print (val.data)
        if((val.right  is not None)):
            stack.append(val.right)
        if((val.left  is not None)):
            stack.append(val.left)

###DFS ITERATIVE FOR GRAPH
def dfs_iter_graph(g,len):
    visited = [False]*len
    stack = []
    stack.append(0)
    visited[0]=True
    while(stack):
        val = stack.pop()
        print(val)

        for i in g.graph[val]:
            if i is not None:
                if(visited[i] == False):
                    stack.append(i)
                    visited[i] = True


##INORDER RECURSIVE AND ITERATIVE###########
def inorder(root):
    if(root):
        inorder(root.left)
        print (root.data)
        inorder(root.right)



def inorder_iter(root):
    current =root
    stack = []

    done = 0
    while(not done):
        if(current is not None):

            stack.append(current)
            current =current.left



        else:
            if(stack):
                current = stack.pop()
                print(current.data)

                current = current.right
            else:
                done =1





######BFS WITH QUEUE

def BFS(root,length):
    L = queue.Queue(maxsize=10)
    visited = [False]*length
    L.put(0)
    visited[0] = True
    while( not L.empty()):
        val = L.get()
        print(val)

        for i in g.graph[val]:
            if i is not None:
                if(visited[i] == False):
                    L.put(i)
                    visited[i] == True











root = node(5)
root.left = node(4)
root.right = node(10)
root.left.left = node(3)
root.right.right = node(15)
# inorder_iter(root)
# dfs_iter(root)






g = DFS()
g.graph[0].append(1)
g.graph[0].append(2)
g.graph[1].append(3)
g.graph[1].append(4)
g.graph[2].append(5)
g.graph[2].append(6)
g.graph[3].append(None)
g.graph[3].append(None)
g.graph[4].append(None)
g.graph[4].append(None)
g.graph[5].append(None)
g.graph[5].append(None)
g.graph[6].append(None)
g.graph[6].append(None)
# g.dfs_recursive(0)len = len(g.graph)
print (len)

# dfs_iter_graph(g,len)BFS(g,len)

Sunday, April 8, 2018

Merge sort and quick sort in python

Merge Sort:

def merge_sort(sor):
    mid = len(sor)//2    
    if(len(sor)<=1):
        return sor


    left =merge_sort(sor[0:mid])
    right = merge_sort(sor[mid:])
    i=j=0 
    tar =0   
    while(i<len(left) and j<len(right)):
        if(left[i]<right[j]):
            sor[tar]=left[i]
            i = i+1        
        else:
            sor[tar] =right[j]
            j=j+1 
        tar =tar+1    
    while(i<len(left)):
        sor[tar] =left[i]
        i =i +1        
        tar=tar+1    
    while(j<len(right)):
        sor[tar]= right[j]
        j=j+1        
        tar =tar+1
    return sor


if __name__ =='__main__':
    arr = [150,4,9,26,1,5,65,2,12,1,1]
    final =merge_sort(arr)
    print (final)





Quick Sort:

def partition(arr,l,h):
    # Note for finding the pivot element and placing the pivot element in middle    
    #  start from initial index and then increase one pointer j to teh last greatest element 
   #   if small element is found swap small element with bigger that is pointed by the j pointer 
   #   
    pivot = arr[h]
    j=l
    for i in range(l,h):
        if(arr[i]<pivot):
            arr[i],arr[j]=arr[j],arr[i]
            j=j+1    arr[j],arr[h]=arr[h],arr[j]
    return  j

def quick_sort(arr,l,h):
    if(l<h):
        pivot = partition(arr,l,h)
        quick_sort(arr,l,pivot-1)
        quick_sort(arr,pivot+1,h)


if __name__ =='__main__':
    arr = [150,4,9,26,8,100,80,12]
    n= len(arr)
    quick_sort(arr,0,n-1)
    print (arr)

Binary tree creation and inorder,preorder traversal both iterative and recurrence in python

class node:
    def __init__(self,key):
        self.data=key
        self.left= None
        self.right =None
def insert(root,nd):
    if(nd.data <= root.data):
        if(root.left is None):
            root.left = nd
        else:
            insert(root.left,nd)
    else:
        if(root.right is None):
            root.right = nd
        else:
            insert(root.right,nd)
def bin_search(root,key):
    if(root is None or root.data == key):
        return root
    else:
        if(key<root.data):
            return bin_search(root.left,key)
        else:
            return bin_search(root.right,key)


def tree_inorder_traverse(node):
    if(node == None):
        return    tree_inorder_traverse(node.left)
    print(node.data)
    tree_inorder_traverse(node.right)

def inorder_iterative(node):
    stack = []
    current = node
    while(1):
        if(current is not None):
            stack.append(current)
            current = current.left
        else:
            if(len(stack)>0):
                current = stack.pop()
                print(current.data)
                current = current.right
            else:
                break
def preorder_traversal(node):
    if(node == None):
        return    print(node.data)
    preorder_traversal(node.left)

    preorder_traversal(node.right)

def preorder_iterative(root):
    stack_pre=[]
    current = root
    while(1):
        if(current is not None):
            print(current.data)
            stack_pre.append(current)
            current =current.left
        else:
            if(len(stack_pre)>0):
                current = stack_pre.pop()
                current = current.right

            else:
                break

def preorder_iterative2(root):
    stack_pre=[]
    current = root
    stack_pre.append(current)
    while(len(stack_pre)>0):
        current = stack_pre.pop()
        print (current.data)
        if(current.right is not None):
            stack_pre.append(current.right)
        if(current.left is not None):
            stack_pre.append(current.left)


if __name__ == "__main__":
    root = node(50)
    insert(root,node(20))
    insert(root,node(70))
    insert(root,node(10))
    insert(root,node(30))
    insert(root,node(60))
    preorder_traversal(root)
    value = bin_search(root,20)
    print (value.data)

    print ("iterative")
    preorder_iterative(root)

Tuesday, February 13, 2018

reading of chunk of data from the binary file and unpacking the data using struct construct in python

import struct

class parser():
    def __init__(self):
        self.data = ""        self.offset = 0
    def add_data(self,data):
        self.data = self.data[self.offset:]
        # print (self.data)        
        self.data += data
        self.offset = 0

    def parse_header(self):
        l,n = struct.unpack('>hh',self.data[self.offset: self.offset+4])
        if len(self.data) - self.offset >l:
            status = True        
        else:
            status = False
        return l,n,status



    def parse_QuoteORTrade_data(self):
        val,type = struct.unpack('>hs',self.data[self.offset:self.offset+3])
        # print(val,type)        
        self.update_offset(3)
        if(type == b'Q'):

            # sym,price,size = struct.unpack('>5shh',self.data[self.offset:self.offset+9])            self.update_offset(17)
            # print (sym,price,size)            
            self.update_offset(val-20)
        if(type == b'T'):

            sym,price,size = struct.unpack('>5shq',self.data[self.offset:self.offset+15])
            self.update_offset(15)
            print (sym,price,size)
            self.update_offset(val-18)




    def update_offset(self,offset):
        self.offset = self.offset+ offset

def ReadInChunk(fileobj,ChunkSize= 50):
    while True:
        data = fileobj.read(ChunkSize)
        if not data:
            break
        yield data



def read_file():
    f = open("input.dat","rb")
    return  f



if __name__ == "__main__" :
    offset_chunk = 0    obj=parser()
    fp = read_file()

    for chunk in ReadInChunk(fp):

        obj.add_data(chunk)
        # print (obj.data)       
        while True:
            try:
                length,num,status = obj.parse_header()


            except Exception,e:
                break            
            if(status == False):
                break
            obj.update_offset(4)
            for data in range(num):

                obj.parse_QuoteORTrade_data()





    fp.close()

Thursday, October 19, 2017

Binary tree creation and sorting with inorder traversal using python

class node:

    def __init__(self,data):
        self.left = None
        self.right = None
        self.data = data



    def insert(self,data):
        if(data<self.data):
            if self.left is None:
                self.left = node(data)
            else:
                self.left.insert(data)

        elif(data>self.data):
            if self.right is None:
                self.right = node(data)
            else:
                self.right.insert(data)

        else:
            self.data =data


def check_inorder(root):
    if(root is not None ):
        check_inorder(root.left)
        print (root.data)
        check_inorder(root.right)


def main():


    root = node(8)
    root.insert(5)
    root.insert(10)
    root.insert(1)


    check_inorder(root)




main()

Saturday, June 7, 2014

Extracting the content of the webpage using BeautifulSoup and Mechanize in python

There arises several condition to extract the content of the page and display in our application. In such case we can use the BeautifulSoup and Mechanize python package.

The python code to extract the price of gold and silver form the website http://www.fenegosida.org/ is shown here


''''Reap gold price from http://www.fenegosida.org/

<h1> tag contains the prices. These h1 resides in following IDS + "-content"

Sample data
{'tejabi-1tola': u'53450', 'hallmark-1tola': u'53700', 'hallmark-10gms': u'46040', 'silver-1tola': u'860', 'tejabi-10gms': u'45825', 'silver-10gms': u'737.50'}
"""

URL = "http://www.fenegosida.org/"
IDS=["hallmark","tejabi","silver"]

import sys
from BeautifulSoup import BeautifulSoup
from mechanize import Browser

if len(sys.argv) > 1 and sys.argv[1] == "-sample":
    print "{'tejabi-1tola_new': u'53450', 'hallmark-1tola': u'53700', 'hallmark-10gms': u'46040', 'silver-1tola': u'860', 'tejabi-10gms': u'45825', 'silver-10gms': u'737.50'}"
    sys.exit(0)

br = Browser()
br.addheaders = [
    ('user-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3',),
    ('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',),
    ]
page = br.open(URL)
soup = BeautifulSoup(page.read())
price = {}

for id in IDS:
    hallmark = soup.findAll('div',{'id':"{0}-content".format(id)})
    
    a = hallmark[0].h1.text
    b = hallmark[1].h1.text

    if float(a) > float(b):
        a, b = b, a

    price['{0}-10gms'.format(id)] = a
    price['{0}-1tola'.format(id)] = b

print price

sys.exit(0)