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()

Tuesday, February 6, 2018

Binary Tree creation with c++ using class and inorder traversal without recursion

//// Created by Laxmi Kadariya on 2/5/18.
//This is the source code to create binary tree with class in c++//#include "iostream"#include <stack>using namespace std;
struct node{

    int item;
    struct node *left;
    struct node *right;
};

class bst{

    private:
         struct node *root;

    public:


    struct node* insert_node(node *root,int item)
    {
      if(root == NULL) {
          root = new node;
          root->item = item;
          root->left = NULL;
          root->right = NULL;
      }

        else{

          if(root->item< item)
          {
            root->left =  insert_node(root->left,item);
          }
          else if(root->item >item)
          {
             root->right = insert_node(root->right,item);

          }
      }

        return root;

    }

    /*Method to print inorder traversal of a BST*/   
 void inorder(node *root)
    {
        stack<node*> stack;
        node *curr=root;
        while(!stack.empty() || curr!=NULL)
        {
            /*If current node is not NULL push the node in stack*/            
           if(curr!=NULL)
            {
                stack.push(curr);
                curr=curr->left;
            }
                /*If current node is empty or NULL pop it from the stack */           
           else           
            {
                curr=stack.top();
                stack.pop();
                cout<<curr->item<<" ";
                curr=curr->right;
            }
        }
    }





};



int main()
{
    bst tree;
    struct node *root = NULL;
    root = tree.insert_node(root,1);
    tree.insert_node(root,2);
    tree.insert_node(root,13);
    tree.insert_node(root,4);

    tree.inorder(root);

}

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()

Wednesday, October 18, 2017

binary tree creation and inorder traversal for sorting implemented in c++

//// Created by Laxmi Kadariya on 10/17/17.//
#include "iostream"using namespace std;

struct node{
    int key;
    struct node *left,*right;

};

struct node *newNode(int item)
{
    struct node *temp = new node;
    temp->key = item;
    temp->left = NULL;
    temp->right = NULL;
    return temp;


}

struct node*  insert(node *node,int key)
{
    if (node == NULL)
    {
        return newNode(key);
    }
    if(key<node->key)
    {
        node->left = insert(node->left,key);
    }

    else if(key>node->key)
    {
        node->right = insert(node->right,key);
    }

    return node;

}



struct node* create_binary_tree(int arr[],int n)
{
    struct node *root = NULL;
    root = insert(root,arr[0]);
    for(int i=1;i<n;i++)
    {
        insert(root,arr[i]);
    }

    return root;

}

void storeSorted(node *root, int arr[], int &i)
{
    if (root != NULL)
    {
        storeSorted(root->left, arr, i);
        arr[i++] = root->key;
        storeSorted(root->right, arr, i);
    }
}




int main()
{
    int arr[] = {5,4,7,2,11};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int i =0;
    struct node *root = create_binary_tree(arr,n);

    storeSorted(root,arr,i);

    for (int i=0; i<n; i++)
        cout << arr[i] << " ";







}

Monday, July 17, 2017

Implementation of singly List insertion, deletion with Class in c++

This article explains the concept of singly link list data structure and provides the simple implementation
in C++.



//// Created by Laxmi Kadariya on 7/15/17.//
#include <iostream>using namespace std;


class node{
private:
    int value;
    node* next;

public:
    node(){

    }

    void set_value(int value_arg){
        value = value_arg;
    }

    void set_next(node* next_arg)
    {
        next = next_arg;
    }

    int show_value(){
        return value;

    }

    node* show_next()
    {
        return next;
    }






};

class linklist{
private:
    node* head;

public:
    linklist(){
        head = NULL;
    }
    void add_node(int value);
    void display_node();
    int length_list();
    void del( int value);


};

void linklist::add_node(int value) {
    node *Node = new node();
    Node->set_value(value);
    Node->set_next(NULL);

    node* tmp = head;

    if(tmp == NULL)
    {
        head = Node;


    }
    else    {
        while(tmp->show_next() != NULL)
        {
            tmp = tmp->show_next();
        }
        tmp->set_next(Node);
    }

  cout<<"node"<<value<< "added"<<endl;

}
int linklist::length_list() {
    int len = 0;
    node* tmp = head;


    while(tmp->show_next() != NULL){
        tmp = tmp->show_next();
        len = len+1;

    }

    return len+1;

}

void linklist::del(int value) {

    node* tmp = head;
    node* prev;

  while(tmp->show_next() != NULL)
  {
      if(tmp->show_value() == value)
      {
          if(head->show_value() == tmp->show_value())
          {
              head = head->show_next();
          }

          else{

              prev->set_next(tmp->show_next());

          }


          delete tmp;
          break;
      }
      else{
          prev=tmp;

          tmp = tmp->show_next();
      }
  }
    if(tmp->show_next() == NULL and tmp->show_value() == value)
    {
        if(head->show_next() == NULL and head->show_value() == value)
        {
            head = NULL;
            delete tmp;
        }

        else        {

            prev->set_next(tmp->show_next());
            delete tmp;
        }
    }


}

void linklist::display_node() {

    node* tmp = head;

    while(tmp->show_next() != NULL)
    {
        std::cout << tmp->show_value()<<endl;
        tmp = tmp->show_next();
    }

    std::cout << tmp->show_value()<<endl;




}
int main(){
    linklist list;
    list.add_node(10);
    list.add_node(20);
    list.add_node(30);
    list.add_node(40);
    list.add_node(50);
    list.display_node();
    int size = list.length_list();
    cout<<size<<endl;
    list.del(30);
    list.display_node();
     size = list.length_list();
    cout<<size<<endl;

}

Thursday, February 23, 2017

Bellman-ford algorithm implementation in Java, and C

Bellman Ford algorithm is an algorithm of finding shortest path in a graph from the given source.

let us take an example of a graph:


Source Code in C:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <limits.h>
struct Edge
{
int src,dst,wt;
};

struct Graph
{
int V,E;
struct Edge *edge;

};

void printArr(int dist[], int n)
{
    printf("Vertex   Distance from Source\n");
    for (int i = 0; i < n; ++i)
        printf("%d \t\t %d\n", i, dist[i]);
}

void BellmanFord(struct Graph* graph, int src)
{
    int V = graph->V;
    int E = graph->E;
    int dist[V];

    // Step 1: Initialize distances from src to all other vertices
    // as INFINITE
    for (int i = 0; i < V; i++)
        dist[i]   = INT_MAX;
    dist[src] = 0;

  
    for (int i = 1; i <= V-1; i++)
    {
        for (int j = 0; j < E; j++)
        {
            int u = graph->edge[j].src;
            int v = graph->edge[j].dst;
            int weight = graph->edge[j].wt;
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                dist[v] = dist[u] + weight;
        }
    }

   
    for (int i = 0; i < E; i++)
    {
        int u = graph->edge[i].src;
        int v = graph->edge[i].dst;
        int weight = graph->edge[i].wt;
        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
            printf("Graph contains negative weight cycle");
    }

    printArr(dist, V);

    return;
}

int main()
{
   printf(" this is the first program\n");
   int vertex =5;
   int edge =8;
   struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
   graph->V = vertex;
   graph->E = edge;
   graph->edge= (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );


   //add the node for vertex A -B
   graph->edge[0].src = 0;
   graph->edge[0].dst = 1;
   graph->edge[0].wt = -1;


    //add the node for vertex A-C
   graph->edge[1].src = 0;
   graph->edge[1].dst = 2;
   graph->edge[1].wt = 4;
   
      //add the node for vertex B-C
   graph->edge[2].src = 1;
   graph->edge[2].dst = 2;
   graph->edge[2].wt = 3;

      //add the node for vertex B-D
   graph->edge[3].src = 1;
   graph->edge[3].dst = 4;
   graph->edge[3].wt = 2;


      //add the node for vertex  B-E
   graph->edge[4].src = 0;
   graph->edge[4].dst = 1;
   graph->edge[4].wt = -1;


      //add the node for vertex E-D
   graph->edge[5].src = 4;
   graph->edge[5].dst = 3;
   graph->edge[5].wt = -3;


      //add the node for vertex D-B
   graph->edge[6].src = 3;
   graph->edge[6].dst = 1;
   graph->edge[6].wt = 1;


      //add the node for vertex D-C
   graph->edge[7].src = 3;
   graph->edge[7].dst = 2;
   graph->edge[7].wt = 5;  

   BellmanFord(graph, 0);

    return 0;



}



Source Code in Java:

/** * Created by laxmikadariya on 2/15/17. */
import java.util.*;
import java.lang.*;
import java.io.*;


class Graph{

    int V,E;

    class Edge{
        int src, dst,wt;
        Edge(){
            src=dst=wt=0;
        }


    }
    Edge edge[];

    Graph(int v,int e)
    {
        V=v;
        E=e;
        edge = new Edge[e];
        for (int i=0;i<e;i++)
        {
            edge[i]=new Edge();
        }


    }

    void BellmanFord(Graph graph,int src)
    {
        int V = graph.V, E = graph.E;
        int dist[] = new int[V];

              for (int i=0; i<V; ++i)
            dist[i] = Integer.MAX_VALUE;
        dist[src] = 0;

         for (int i=1; i<V; ++i)
        {
            for (int j=0; j<E; ++j)
            {
                int u = graph.edge[j].src;
                int v = graph.edge[j].dst;
                int weight = graph.edge[j].wt;
                if (dist[u]!=Integer.MAX_VALUE &&
                        dist[u]+weight<dist[v])
                    dist[v]=dist[u]+weight;
            }
        }

       
        for (int j=0; j<E; ++j)
        {
            int u = graph.edge[j].src;
            int v = graph.edge[j].dst;
            int weight = graph.edge[j].wt;
            if (dist[u]!=Integer.MAX_VALUE &&
                    dist[u]+weight<dist[v])
                System.out.println("Graph contains negative weight cycle");
        }
        System.out.println("Vertex   Distance from Source");
        for (int i=0; i<V; ++i)
            System.out.println(i+"\t\t"+dist[i]);
    }


}
public class bellmon_ford {


    public static void main(String[] args) {
        int V = 5;
        int E = 8;
        Graph graph =  new Graph(V,E);



        //add the node for vertex A -B        
        graph.edge[0].src=0;
        graph.edge[0].dst = 1;
        graph.edge[0].wt = -1;


        //add the node for vertex A-C       
        graph.edge[1].src = 0;
        graph.edge[1].dst = 2;
        graph.edge[1].wt = 4;

        //add the node for vertex B-C        
        graph.edge[2].src = 1;
        graph.edge[2].dst = 2;
        graph.edge[2].wt = 3;

        //add the node for vertex B-D       
         graph.edge[3].src = 1;
        graph.edge[3].dst = 4;
        graph.edge[3].wt = 2;


        //add the node for vertex  B-E       
        graph.edge[4].src = 0;
        graph.edge[4].dst = 1;
        graph.edge[4].wt = -1;


        //add the node for vertex E-D        
        graph.edge[5].src = 4;
        graph.edge[5].dst = 3;
        graph.edge[5].wt = -3;


        //add the node for vertex D-B        
        graph.edge[6].src = 3;
        graph.edge[6].dst = 1;
        graph.edge[6].wt = 1;


        //add the node for vertex D-C        
        graph.edge[7].src = 3;
        graph.edge[7].dst = 2;
        graph.edge[7].wt = 5;

        graph.BellmanFord(graph, 0);



    }
}


Thursday, February 9, 2017

Reversing each word of the string with blank space preserved in Python and Java

we can come in the situation that we need to reverse each word of the string and also we need to preserve the blank space i.e we may have more than one space character in between each word and that needs to be preserved as well. Here I have mentioned the code for Python and Java.

Input:   "   I         am Laxmi     Kadariya"
Output:     I         ma imxaL     ayiradaK 

Algorithm:
1) split the string in to words:
2) reverse each word
3) finally join all the reverse word with space
def rev_string(test):
 final_str = ''
 words = test.split(' ')
 for x in words:
  rev_word = x[::-1]
  final_str = final_str + rev_word + ' ' 

 print final_str


 
  



if __name__ == '__main__':
 test = "   I         am Laxmi     Kadariya"
 rev_string(test)

Java Code:

/**
 * Created by laxmikadariya on 2/8/17.
 */
public class string_rev {
    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");

        String reverseString = "";

        for (int i = 0; i < words.length; i++)
        {
            String word = words[i];


            String reverseWord = "";

            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }

            reverseString = reverseString + reverseWord + " ";
        }

        System.out.println(inputString);

        System.out.println(reverseString);

        System.out.println("-------------------------");
    }

    public static void main(String[] args)
    {
        reverseEachWordOfString("   I am     Laxmi Kadariya");

    }
}