Saturday, April 4, 2020

OOPS Python : Create Class

class Country():
    # Class object Attribute
    area = 3287000
    def __init__(self,name,population):
        self.population = population
        self.name=name
    def describe(self):
        print("population of {} is {}".format(self.name,self.population))
        #print("Area sq km of {} is {}".format(self.name,self.area)) also
        print("Area sq km of {} is {}".format(self.name,Country.area))
       
    def update_population(self,new_population):
        self.population = new_population
       
c1 = Country('India',1300000000)
c1.update_population(1350000000)
c1.describe()

Thursday, April 2, 2020

Theano prompts to install m2w64-toolchain to improve performance

WARNING (theano.configdefaults): g++ not available, if using conda: `conda install m2w64-toolchain`
WARNING (theano.configdefaults): g++ not detected ! Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded.


Steps to Install in Anaconda:
  • conda install msys2/m2w64-toolchain
  • anaconda search -t conda msys2/m2w64-toolchain
  • anaconda show msys2/m2w64-toolchain
  • conda install --channel https://conda.anaconda.org/msys2 m2w64-toolchain

Indexer for search engine in python

import sys
import os
import urllib
import re
from bs4 import BeautifulSoup
#first time
#from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED ,NUMERIC
#from whoosh.index import create_in, open_dir
#from whoosh.query import *
import whoosh.index as index
ix = index.open_dir("index")
#then onwards
from whoosh.analysis.tokenizers import RegexTokenizer
from whoosh.analysis.tokenizers import IDTokenizer
#--------------------------------------------------------------------------------------
#creating the schema
schema = Schema(lid= TEXT(stored=True),ldata=TEXT(stored=True))
#creating the index
if not os.path.exists("index"):
    os.mkdir("index")
ix = create_in("index",schema)
ix = open_dir("index")
writer = ix.writer()
#--------------------------------------------------------------------------------------
soup = BeautifulSoup(open("39/390099"))
#tag = soup.find('title')
#print(tag.text)
#print(soup.prettify())
#for link in soup.find_all('a'):
#   print(link.get('href'))
#print(soup.get_text())
text1=soup.get_text()
text2=text1.split()

def LowercaseFilter(tokens):
    for t in tokens:
        t.text = t.text.lower()
        yield t

regt = RegexTokenizer()
idt = IDTokenizer()
#-----------------------------------------------------------------------------

for token in regt(text1):
   writer.add_document(lid=unicode(LowercaseFilter(token.text.encode('utf-8'))),ldata=unicode(LowercaseFilter(token.text.encode('utf-8'))))
   break
   #print unicode(token.text.encode('utf-8'))
  
#length=len(words_list)


 
   #print unicode(token) , fdist1[token]
 
   #print words_list[i]


#------------------------------------------------------------------------------------------------------

testVar=raw_input("enter a search keyword : ")
from whoosh.qparser import QueryParser
ix.searcher().documents()
with ix.searcher() as searcher:
    #query = QueryParser("ldata", ix.schema).parse(u'methylotrophus')
    query = QueryParser("ldata", ix.schema).parse(testVar)
    results = searcher.search(query)
    for result in results:
        print result

are python strings mutable ?

No python strings are not mutable.
That means you cannot use indexing to change individual characters in a string in python.

pip install to a local folder , pip install from a local folder

pip install to a local folder 
pip download --dest localpip/ --find-links localpip/ requests

pip install from a local folder
pip --find-links localpip/ numpy

apt-get install to a folder of your choice

sudo apt-get install --download-only 'required-library' -o Dir::Cache::archives='path to your folder'

example path = '/home/ubuntu/test/'
example required library =  numpy 

find all the substrings in a python string

def find_subs(s):
  n = len(s)
  return [s[i:j + 1] for i in range(n) for j in range(i,n)]

Fibonacci series starting with any two numbers

def multiply(F, M):
    x = (F[0][0] * M[0][0] + F[0][1] * M[1][0])
    y = (F[0][0] * M[0][1] + F[0][1] * M[1][1])
    z = (F[1][0] * M[0][0] + F[1][1] * M[1][0])
    w = (F[1][0] * M[0][1] + F[1][1] * M[1][1])
    F[0][0] = x
    F[0][1] = y
    F[1][0] = z
    F[1][1] = w
   
def power(F, n):
    if( n == 0 or n == 1):return
    M = [[0, 1],[1, 1]] 
    power(F, n // 2)
    multiply(F, F)
    if (n % 2 != 0):
        multiply(F, M) 


def fib(a,b,n):
     
    F = [[0, 1],[1, 1]]
    if (n == 0): return a
    if (n == 1): return b
    power(F, n - 1)
         
    return F[0][1]*a + F[1] [1]*b

How to initialize dynamic variables

Example 1:


Example 2 :
 
str[i] = malloc(len(char)*5)

Why lowercase variable is used other than uppercase?

Practically speaking variables should be allowed in any case, but just to follow convention in a particular domain we use certain format of words.
For example Class-names usually start with  UPPERCASE and if you want to use same name for object it can be only possible by using lowercase.

Monday, February 18, 2019

python remove text from string after character(s) without using regex

pivot = '...'
required = text.split(pivot, 1)[0]

regex to find datetime in text format

import re
r = re.compile('(?P<dow>[a-zA-Z]+,) (?P<date>[0-9]{2}) (?P<month>[A-Za-z]+) (?P<year>[0-9]{4}) (?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}) (?P<ampm>[A-Z]{2})')

s = "Monday, 14 January 2019 11:50 PM"

print([m.groupdict() for m in r.finditer(s)][0])


output :
 
{'dow': 'Monday,', 'date': '14', 'month': 'January', 'year': '2019', 'hour': '11', 'minute': '50', 'ampm': 'PM'}

Wednesday, December 14, 2016

Merge Sort in c++

#include<iostream>
#include<vector>
using namespace std;
 
void merge(vector<int> &v,int l, int m,int r)
  {
    vector<int> a(v.begin()+l,v.begin()+m+1);
    vector<int> b(v.begin()+m+1,v.begin()+r+1);
    int ptr1=0,ptr2=0,ptr=l;
    while(ptr1<a.size() && ptr2<b.size())
        if(a[ptr1]<b[ptr2])
            v[ptr++]=a[ptr1++];
        else
            v[ptr++]=b[ptr2++];
    while(ptr1<a.size())
        v[ptr++]=a[ptr1++];
    while(ptr2<b.size())
        v[ptr++]=b[ptr2++];
  }

void mergesort(vector<int> &vec,int l,int r )
   {
      if(l<r)
       {
           int m=(l+(r-1))/2;
           mergesort(vec,l,m);
           mergesort(vec,m+1,r);
           merge(vec,l,m,r);
       }
   }

int main()

  {

    int arr[] ={99,8,22,11,44,55,2,1,5,26,98,8,888,36,99,75,48,74,587,4};
    vector<int> vec(arr,arr+sizeof(arr)/sizeof(int));
    mergesort(vec,0,(vec.size())-1);
    for(int i=0;i<vec.size();i++)
        cout<<vec[i]<<" ";
    return 0;

  }

Monday, November 14, 2016

C++ Program to print a 2-d matrix/vector in spiral order

vector<int> spiralOrder(const vector<vector<int> > &A)

{

    vector<int> result;
    long min_x=0,min_y=0,done=0,count=0,i=0,j=0;
    long n,max_x=A[0].size()-1, m,max_y=A.size()-1;
    long size=(max_x+1)*(max_y+1);
    while(count<size)
        {  
            if(i==min_y && j==min_x)
                {  if(done==1)
                       { min_x++;min_y++;max_x--;max_y--;i=min_y;j=min_x;  }
                    else done=1;
                }
            result.push_back(A[i][j]);
            count++;
            if(i==min_y && j<max_x)        j++;
            else if(i==min_y && j==max_x)  i++;
            else if(i<max_y && j==max_x)   i++;
            else if(i==max_y && j==max_x)  j--;
            else if(i==max_y && j>min_x)   j--;
            else if(i==max_y && j==min_x)  i--;
            else if(i>min_y && j==min_x)   i--;
        }
    return result;
}

Sunday, June 26, 2016

Python code for Quick Sort using original Hoare partition scheme


from random import randint
def quicksort(array, low, high):
    if low < high:
        p = partition(array, low, high)
        quicksort(array, low, p)
        quicksort(array, p + 1, high)

def partition(array, low, high):
    pivot = array[low]
    i=low-1
    j=high+1
    while 1:
    i = i + 1
        while array[i] < pivot:
            i = i + 1
        j=j-1
        while array[j] > pivot:
            j=j-1
       
        if i >= j:
            return j
        array[i],array[j]=array[j],array[i]




array=[]
for p in range(10):
    array.append(randint(1,100))

quicksort(array,0,len(array)-1)
print array

Sunday, March 20, 2016

Implementation of iterative deepening A* (Star) Algorithm

#node              current node
#g                 the cost to reach current node
#f                 estimated cost of the cheapest path (root..node..goal)
#h(node)           estimated cost of the cheapest path (node..goal)
#cost(node, succ)  step cost function
#is_goal(node)     goal test
#successors(node)  node expanding function
V={}
E={}
V=({'A':7,'B':9,'C':6,'D':5,'E':6,'F':4.5,'H':4,'I':2,'J':3,'K':3.5,'G':0})
E=({('B','D'):2,('A','B'):4,('A','C'):4,('A','D'):7,('D','E'):6,('E','F'):5,('D','F'):8,('D','H'):5,('H','I'):3,('I','J'):3,('J','K'):3,('K','H'):3,('F','G'):5})
INFINITY=10000000
cameFrom={}
def h(node):
    return V[node]
def cost(node, succ):
    return E[node,succ]

def successors(node):
    neighbours=[]
    for item in E:
        if node==item[0][0]:
            neighbours.append(item[1][0])
    return neighbours

def reconstruct_path(cameFrom, current):
    total_path = [current]
    while current in cameFrom:
        current = cameFrom[current]
        total_path.append(current)
    return total_path
   
def ida_star(root,goal):
    global cameFrom
    def search(node, g, bound):
        min_node=None
        global cameFrom
        f = g + h(node)
        if f > bound:return f
        if node==goal:return "FOUND"
        minn = INFINITY
        for succ in successors(node):
            t = search(succ, g + cost(node, succ), bound)
            if t == "FOUND":return "FOUND"
            if t < minn:
                minn = t
                min_node=succ
        cameFrom[min_node]=node
        return minn
       
    bound= h(root)
    count =1
    while 1:
        print "itertion"+str(count)
        count+=1
        t = search(root, 0, bound)
        if t == "FOUND":
            print reconstruct_path(cameFrom, goal)
            return bound
        if t == INFINITY:return "NOT_FOUND"
        bound = t
  
print ida_star('A','G')
   

Friday, March 18, 2016

Implementation of A* algorithm in python


V={}
E={}
V=({'A':7,'B':9,'C':6,'D':5,'E':6,'F':4.5,'H':4,'I':2,'J':3,'K':3.5,'G':0})
E=({('B','D'):2,('A','B'):4,('A','C'):4,('A','D'):7,('D','E'):6,('E','F'):4.5,('D','F'):8,('D','H'):4,('H','I'):3,('I','J'):3,('J','K'):3,('K','H'):3,('F','G'):5})



INFINITY=10000000
def find_neighbours(node):
    neighbours=[]
    for item in E:
        if node==item[0][0]:
            neighbours.append(item[1][0])
    return neighbours
   


def reconstruct_path(cameFrom, current):
    total_path = [current]
    while current in cameFrom:
        current = cameFrom[current]
        total_path.append(current)
    return total_path
    #

def Astar(start, goal):
   
    current = start
    fScore={}
    gScore={}
   
   
   
   
    # The set of currently discovered nodes still to be evaluated.
    openSet = set()
    # The set of nodes already evaluated.
    closedSet = set()
    # Initially, only the start node is known.
    openSet.add(current)
   
    # For each node, which node it can most efficiently be reached from.
    # If a node can be reached from many nodes, cameFrom will eventually contain the
    # most efficient previous step.
    cameFrom ={}#the empty map

    # For each node, the cost of getting from the start node to that node.
    for node in V:
        gScore[node] = INFINITY #map with default value of Infinity
    # The cost of going from start to start is zero.
    gScore[start] = 0
    # For each node, the total cost of getting from the start node to the goal
    # by passing by that node. That value is partly known, partly heuristic.
    for node in V:
        fScore[node] = INFINITY #map with default value of Infinity
    # For the first node, that value is completely heuristic.
    fScore[start] = V[start]#heuristic_cost_estimate(start, goal)
   
    def heuristic_cost_estimate(node, goal):
    return E[cameFrom[node],node]+V[node]
    count=0
    while openSet:
        count+=1
        if count>10:
            break
        print openSet
        minn=INFINITY
        for node in openSet:
            if fScore[node]<minn:
                current=node
        if current==None:
            current=start
        #current = node in openSet having the lowest fScore[] value)
        if current == goal:
            return reconstruct_path(cameFrom, goal)

        openSet.remove(current)
        #Add it to the closed set
        closedSet.add(current)
        for neighbor in find_neighbours(current):
            if neighbor in closedSet:
                continue        # Ignore the neighbor which is already evaluated.
            # The distance from start to goal passing through current and the neighbor.
            tentative_gScore = gScore[current] + E[(current, neighbor)]
            if neighbor not in openSet:    # Discover a new node
                openSet.add(neighbor)
            elif tentative_gScore >= gScore[neighbor]:
                continue        # This is not a better path.

            # This path is the best until now. Record it!
            cameFrom[neighbor] = current
            gScore[neighbor] = tentative_gScore
            fScore[neighbor] = gScore[neighbor] + heuristic_cost_estimate(neighbor, goal)

    return "failure"



print Astar('A','K')

Tuesday, December 8, 2015

Read very large strings of UNKNOWN length

char buffer[10];
    char *s = 0;
    size_t cur_len = 0;
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        size_t buf_len = strlen(buffer);
        char *extra = realloc(s, buf_len + cur_len + 1);
        if (extra == 0)
            break;
        s = extra;
        strcpy(s + cur_len, buffer);
        cur_len += buf_len;
    }

Friday, November 6, 2015

Graph implementation using adjacency list

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int key;
    struct node * next;
}node;
typedef struct list
{
    struct node * head;
}list;
typedef struct GRAPH
{
    int V;
    struct list * array;
}GRAPH;
node * newnode(int k)
{
    node *n=(node *)malloc(1*sizeof(node));
    n->key=k;
    return n;
}
GRAPH *newgraph(GRAPH * g,int v)
{   g=(GRAPH *)malloc(sizeof(GRAPH));
    g->V=v;int i;
    g->array=(list *)malloc(v*sizeof(g->array));
    for(i=0;i<v;i++)
         g->array[i].head=NULL;
    return g;
}
void add_edge(GRAPH * g,int s , int t)
{
    node *n=newnode(t);
    n->next=g->array[s].head;
    g->array[s].head=n;
    node *n2=newnode(s);
    n2->next=g->array[t].head;
    g->array[t].head=n2;
}

void delete_edge(GRAPH * g,int s , int t)
{
     if(g->array[s].head==NULL){printf("There is no edge between %d and %d \n", s , t);return;}
    node * ptr1=g->array[s].head;
    if(ptr1->next==NULL)
        {if(ptr1->key==t){free(ptr1);ptr1=NULL;}return;}
    if(ptr1->key==t)
    {  g->array[s].head=ptr1->next;free(ptr1);return;}

    node * ptr2=g->array[s].head->next;

    while(ptr2!=NULL)
    {
        if(ptr2->key!=t)
          {
            ptr1=ptr2;
            ptr2=ptr2->next;
           }
          else break;

    }
   if(ptr2!=NULL)
    {
      if(ptr2->key==t)
        {ptr1->next=ptr2->next;
        free(ptr2);
        }
      else printf("There is no edge between %d and %d \n", s , t);
    }
    else
         printf("There is no edge between %d and %d \n", s , t);

}
void printgraph(GRAPH *g)
{
    int v,i;
    v=g->V;
    for(i=0;i<v;i++)
        {   node * ptr=g->array[i].head;            printf("%d->",i);

            while(ptr!=NULL)
            {
                printf("%d->",ptr->key);
                ptr=ptr->next;
            }
            printf("\n");
        }
}
void remove_edge(GRAPH *graph ,int a , int b)
{   printf("deleting edge %d-%d \n",a,b);
    delete_edge(graph,a,b);delete_edge(graph,b,a);

}
int main()
{   int size=5;
    GRAPH *graph=newgraph(graph,size);
    add_edge(graph,0,1);add_edge(graph,0,2);add_edge(graph,0,4);
    add_edge(graph,1,4);add_edge(graph,1,2);add_edge(graph,1,3);
    add_edge(graph,2,3);add_edge(graph,2,4);
    add_edge(graph,3,4);
    printgraph(graph);
    remove_edge(graph,2,3);
    remove_edge(graph,1,4);
    remove_edge(graph,1,3);


           printgraph(graph);
    printf("success\n");
return 0;
}



Tuesday, October 13, 2015

program to find the linearly dependent columns in multidimensional array

#include<stdio.h>
#include<stdlib.h>
int main()
{

int i,j,k,m,n,len,col,a[9][9]={{2,3,6,5,1,2,3,6,9},{2,3,6,5,4,2,3,6,2},{2,3,6,5,4,2,3,1,9},{2,3,6,5,4,2,3,6,9},{2,3,6,5,4,2,3,6,9},
       {2,3,6,5,4,2,3,6,9},{2,3,6,5,4,3,3,6,9},{2,3,6,5,4,2,4,6,9},{2,3,6,5,8,2,3,6,9}
        };

for(i=0;i<8;i++)
    for(j=i+1;j<9;j++)
{ printf("here");
     if(a[0][i]%a[0][j]==0)
     {  printf("here1");
           len=1;
         col=i;
         for(k=1;k<9;k++)
         {
             if(a[k][i]%a[k][j]!=0)
                 len=0;
         }
       printf("here2");
     }
     else if(a[0][j]%a[0][i]==0)
     {   len=1;printf("here3");
         col=j;
         for(k=1;k<9;k++)
         {   len=1;printf("in55");
             if(a[k][j]%a[k][i]!=0)
                 len=0;
                 printf("in56");
         }
         printf("here4");
     }
     if(len==1)printf("\ncolumn : %d is linearly dependent",col);
}
return 0;
}