Wednesday, August 17, 2011

Fancy custom sorts in Python

So I had a google interview . They shut me down. But they got me thinkin alot about python.



So I had this issue... I have this project that involves sensitivity analysis of some paramters, i.e. doing a calculation with different inputs with the expectation that the result of the calculation will be able to "detect" a good input vs a bad one.



And I want to prove to my boss that either the best inputs, or the worst inputs have a poor (albeit positive) overall correlation to the calculations result.



So I started thinking recursively, in python, and I wrote a script to do this... Except I knew it would take a month to finish. So what I needed, was to optimize the script so that it first tested the boundary conditions, working its way inward.



For example, given a list of inputs (1 expected to yield the best result, 10 expected to yield the worst), we could write an consider a "staggered sort", where you get the following array as a return value :



[1,10,2,9,3,8,...]... Got it ?



In python : About 5 lines of code. Why ? Because of pythons wonderful list : operator.





def staggerSort(li):

n=len(li)-1

if n == 1:

return li;

lR = [];



lR.append(li[0])

lR.append(li[-1])

lR.extend(staggerSort(li[1:n]))



return lR;





Yay Python !

0 comments:

Post a Comment