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

Thursday, April 19, 2012

Python - Somthing similar to curry

Currying is a pretty neat idea. However python has its own partial in functools module.

So, left with nothing better to do, I had an idea of a function that waits till it has been called with the required number of arguments to return the result. That is, the arguments from the previous calls should be saved somewhere and used later.

So, here is the result almost_curry!


class almost_curry():
    def __init__(self,func):
        import inspect as insp
        self.func = func
        self.argsInFunc = insp.getargspec(func)[0]
        self.argsReq = len(self.argsInFunc)
        self.args = []
        self.kwargs = {}
   
    def __call__(self,*args,**kwargs):
        if args:
            self.args.extend(args)
            if len(self.args) == self.argsReq:
                targs = list(self.args)
                self.args = []
                return self.func(*targs)
               
        if kwargs:
            self.kwargs.update(kwargs)
            if len(self.kwargs) == self.argsReq:
                tkwargs = self.kwargs.copy()
                self.kwargs = {}
                return self.func(**tkwargs)


If we have a normal function, say sumxy,


def sumxy(x,y):
    return x+y


Now, we can do something like,
csumxy = almost_curry(sumxy)

If we call the our csumxy (its an object, not a function, but, functions are objects, oh I am getting loopy, never mind...)

csumxy(4) #just a normal call
csumxy(5) #target function has got the required number or args, so
9               # it has output the result! yay!

Takeaway: I found one use for the inspect module in python. Pulling this off without getargspec() in inspect would have required some other kind of hackery. If you have any suggestions please comment.

Friday, December 16, 2011

Some of my Django errors I faced and solved

This post is practically written for my sake alone - so that I'll know what to do later, if I face the same issues again.

Well here I go,

  • "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2":  In django 1.3.1 settings.py file, if the database backed for Postgresql is simply given as 'postgresql' instead of postgresql_psycopg2, django simple gives the error as psycopg module not found. 

  • "django error no module named messages": If you install Ubuntu 10.04's django version, well I have to confess that i never updated, it was a fresh vm, and straightway run your django app, it throws this. Download and install the latest django version. Solved.

  • "django psycopg2.OperationalError: FATAL:  Ident authentication failed for user": Another classy misleading error. Just add 'localhost' in settings.py HOST, even though the helpful comment asks you to just leave it empty.

I LOVE DJANGO!!! This post is just to help another poor soul like me hunting in google and stackoverflow.

Friday, December 2, 2011

Store Credit - Google Code Jam 2010

Here is a solution for Google's Code Jam 2010 Store Credit problem.

In Python the code is very simple. It is a brute force kindda solution.

if __name__ == "__main__":
   
    fin = open('storeInput.inp','r')
    inputdata = fin.readlines()
    fin.close()
   
    it = iter(inputdata)

    numTestCases = int(it.next())
   
    fout = open('storeOutput.txt','w')

    for i in range(1,numTestCases+1):
        str1 = "Case #%d: " %(i)
        fout.write(str1)
       
        mycredit = int(it.next())
       
        num_items = int(it.next())

        items_cost = [int(y) for y in it.next().split()]
       
        found = False
        for j in range(len(items_cost)-1):
            if found:
                break
            for k in range(j+1,len(items_cost)):
                if((items_cost[j]+items_cost[k])==mycredit):
                    fout.write(str(j+1) + " "+ str(k+1) + "\n")
                    found = True
                    break
    fout.close()

In C, code for the same process is as follows,

#include
#include

void process(FILE *fin, FILE *fout)
{
    int storeCredit,I,*p, i,iActual = 0,j;
    fscanf(fin,"%d",&storeCredit);
    fscanf(fin,"%d",&I);
   
    p = (int *)malloc(sizeof(int)*I);
    for(i=0;i   

    for(i=0;i < I - 1; i++)

      for(j = i+1; j < I; j++)
            if((*(p+i) + *(p+j)) == storeCredit)
            {
                fprintf(fout,"%d %d\n",i+1,j+1);
                i = I;
                break;
            }
    free(p);
}

int main()
{
    FILE *fin,*fout;
    int N,i;
    fin = fopen("storeInput.inp","r");
    fout = fopen("storeOutput.txt","w");
   
    fscanf(fin,"%d",&N);
    for(i=0;i    {
        fprintf(fout,"Case #%d: ",i+1);
        process(fin, fout);
    }

    fclose(fin);
    fclose(fout);
}


To make the C code, even faster, I tried another one using pthreads. I'll update that later.

Monday, July 25, 2011

Django in the appengine

I am planning to blog a walk-through in creating and hosting a django based app in the google appengine.

Before I start rambling on my own, let me give you a couple of links which got me going.


If you are unable to make much sense of the third and fourth links, come back here! I'm going to keep this damn simple.

Lets do the doing!!!