Python Code Example

I wrote a piece of python code. It’s a generalised summation function, it sums up arbitrary functions (simple ones alteast!), for an arbitrary number of summations. Inspired by Nikhil’s lisp code, and a “Can I do this in Python attitude!”

Here it is:

def list_inc(list_begin,list_end,list_cur):
	if list_cur ==[ ]:
		return list_cur
	if list_cur[-1] < list_end[-1]:
		list_cur[-1] = list_cur[-1] + 1
		return list_cur
	list_cur= list_inc(list_begin[:-1],list_end[:-1],list_cur[:-1])
	list_cur.append(list_begin[-1])
	return list_cur

def summation(function,list_begin,list_end):
	sum = 0
	list_cur = list_begin
	while (list_cur != list_end):
		sum = sum + apply (function,list_cur)
		list_cur =  list_inc (list_begin,list_end,list_cur)
	sum = sum + apply (function,list_end)
	return sum

 #Arbitrary function, ranges
print summation(lambda x,y,z:x*y*z,[1,1,1],[2,3,5])       

Btw, I think I might have to read up on how to format the code properly while using wordpress. I did use the < "code"> thing, but it's not very impressive. A < "pre"> tag might be good.

About robotgeek

Rocker, philosopher, Mac lover, geek, robotics freak and an optimist. These describe me adequately, i guess! When I find time away from my lab, I love to code my robots using java to be compatible with robocode . I also make it a point to visit Slashdot or read on Wikipedia . Of course, all this has to be done while listening to Pink Floyd, Led Zeppelin, Metallica or Pearl Jam, mostly on Shoutcast online radio . I also like to read. Though I don't find much time now, I generally stick to what I like, which is Ayn Rand. Let's just hope the world heads in the right direction 2004 has been the year of the blog, and I could not be left out!
This entry was posted in code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>