Monday, May 23, 2016

Longest Increasing Sub sequence (LIS) Analysis



Brute Force Solution for LIS

#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[]={ 10, 22, 9, 33, 21, 50, 41, 60 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0)
  return 1;
 else
  return result;
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

int main() {
 printf("%d\n",lcs(8));
 return 0;
}

Here the time complexity is n!

Moving ahead, we can use memoization to optimize the solution.


#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int Mem[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   if (Mem[j] > 0)
    result = max(result,1+Mem[j]);
   else 
    result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0){
  Mem[i] = 1;
  return 1;
 }
 else{
  Mem[i] = result;
  return result;
 }
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

Here I have used Mem[] to remember the result. With this optimization, 
the complexity goes to O(N^2) 

We can also solve this problem using DP (Bottom up approach)
#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int dp[8];

int L(int n){
    int max2 = -1;
    for(int i=1;i<n;i++){
         for( int j=i-1;j>=0;j--){
            if(Arr[i] > Arr[j] && dp[i] < dp[j]+1){
                dp[i] = dp[j]+1;
            } 
             
         }
        max2 = max(max2,dp[i]);
    }
    
    return max2; 
}

int main() {
 for(int i=0;i<8;i++) dp[i] = 1;
 printf("%d\n",L(8));
 return 0;
}


priority queue implementation in c++

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <queue>
using namespace std;
class Foo
{
  public:
int key;
int value;
};

class Compare
{
public:
    bool operator() (Foo Foo1, Foo Foo2)
    {
        return Foo1.value < Foo2.value;
    }
};

int main()
{
    srand(time(NULL));
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    for (int i=0;i<5;i++){
Foo tmp;
tmp.key = i;
tmp.value = rand()%100;
        printf("key %d = value %d\n",tmp.key, tmp.value);
pq.push(tmp);
    }
    while (!pq.empty()){
      Foo tmp = pq.top();
printf("%d = %d\n",tmp.key,tmp.value);
pq.pop();
}
    return 0;
}

output
=====
Success time: 0 memory: 3456 signal:0
key 0 = value 76
key 1 = value 62
key 2 = value 57
key 3 = value 74
key 4 = value 74
0 = 76
3 = 74
4 = 74
1 = 62
2 = 57

Monday, May 16, 2016

Lambda interacting with Redshift #AWS #LAMBDA #REDSHIFT #SNS #Python

'''
Here I am sharing methods to interact with Redshift or Arora DB in AWS, posting message to a given topic in SNS
'''

import json
import urllib2

import hmac
import hashlib
import base64
import string
import psycopg2
from time import strftime,gmtime,time

ACCESS  = 'XXXXXXXXXXXXXXXXXXX'
SECRET  = 'uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                     

REGION  = 'xxxx'
TOPIC   =  'xxxx'
MSG    = 'This is test message xxxxx'
SUBJECT = 'demo2'

'''
Here, the function fetchData will establish a connection with Redshift, execute a query and fetch the data.
'''

def fetchData():
       
    conn = psycopg2.connect(
        host="host_name_apearing_at_aws_console_excluding_port",
        user='myuser',
        port=5439,
        password='password',
        dbname='rdb')

    cur = conn.cursor()
   
    column_names = [];
    cur.execute("select * from dummy limit 10;");
    tmp=cur.fetchall();
   
   #conn.commit()
    conn.close()

'''
Below function will post to SNS
'''
def publishAmazonSnsMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = REGION
  params = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }
 
  cannqs=string.join(["%s=%s"%(urllib2.quote(key),urllib2.quote(params[key], safe='-_~')) \
                                for key in sorted(params.keys())],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')
  sig=base64.b64encode(hmac.new(privatekey,string_to_sign,digestmod=hashlib.sha256).digest())
  url="http://%s/?%s&Signature=%s"%(amzsnshost,cannqs,urllib2.quote(sig))
  print url
 
  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())

def lambda_handler(event, context):
    fetchData()
    try:
        ret = publishAmazonSnsMsg(SUBJECT, TOPIC ,MSG , ACCESS, SECRET)
    except:
        pass

'''
# To test the function from cli
if __name__ == '__main__':
lambda_handler(None, None)
'''
'''

The above method running inside a lamba fuction will connect with the db and post to the SNS. There are some modules which are not available in AWS enviornment. We need to attach the the module folder in the root directory while zipping the module. As example for the above code psycopg2 was not available. So I have attached the module while zipping the source code.

Ex: ++lambda_function.py
       ++ psycopg2
               ++
               ++
In the same way we can attach the custom module too. For the psycopg2, it requires to be statically compiled. I am sharing a git link having the compiled module as well as listing method to compile the same. https://github.com/prrs/awslambda-psycopg2. courtsey: https://github.com/jkehler/awslambda-psycopg2
'''

Sunday, January 17, 2016

django_sentinel

https://github.com/prrs/django_sentinel

Redis sentinel implementation for django redis.