Friday, July 30, 2010

Python in Vim

What if your favorite editor can interpret your favorite language!!! That would make writing code a piece of cake. This is what happened to me recently. I knew Vim could interpret Python. Only after I tried it out, I found how easy it is.

Simply go to normal mode and do :py print 'Vim Roxx' to see what I am trying to tell. You have to include a :py at the start of the line and it runs in Vim just as if it were running on a Python interpreter.

I know how you are feeling. I felt the same way too. Isn't there a way to specify start of python code and end. There is one.
:py << EOF
print "This is cool"
print "I'm lovin it"
EOF

does the job for you. The EOF here is only a name and any variable_name can be used. You can also specify a file to execute by using :pyfile file_name

Here is a quick snippet. I would like to run the Python code from my current buffer. I want to go over a line and press f4 and expect Vim to execute that command by adding a ":py" in the start.

Hence I first do
:py << EOF
import vim
def run_line():
cmd = ":py " + vim.curent.line
vim.command(cmd)
EOF
So now every time I go over a line and type :py run_line() in the normal mode, the current line is run as a line of python code. All I now have to do is bind this function to the required key and nmap <f4> :py run_line() <CR> does the job for me.

Happy Vimming with Python :) :)

Thursday, July 22, 2010

Adding Polynomials

Imagine a polynomial like 2x3 - 3x2 + 5 was represented as a list of coefficients in a list like [1, -3, 0, 5]

My goal is to write a function that takes two lists and does polynomial addition on them. Ex: poly_add( [1, -2, 0, 3, 5] , [3, -1, 2] ) should return [1, -2, 3, 2, 7]

After a little brainstorming, I got this cute idea, which I felt was so cute that I should blog about it. Moreover it has been a while since I have written something.

Here is the function

def poly_add( x, y):
min_len = min( len(x), len(y))
return x[: -min_len] + y[: -min_len] + [ x[i] + y[i] for i in range(-min_len,0) ]

If this is trivial then great. If it is not so trivial, you will love the beauty behind this function and hence python itself.

I use Python and I am loving it :) :) :)