It all sounds Geek to me! [Gautam Arora]

Thursday, August 18, 2005

Lets be more Pythonic ... Part II

The comments in the previous post sure brought abt a miniature py vs ry code-snippet war:

1) List comprehensions
Python: ret=[do_something(elem) for elem in li]
Ruby: ret=li.each {|elem| elem.do_something}

2) return
In Python, all functions return a value; if you dont provide return, your function returns the None object automatically
In Ruby, everything(methods, prodecures, code blocks etc.) returns a value; usually of the last statement executed unless an explicit return statement
(More research required for this point....)

3) each
Python: [do_something(elem) for each in li]
Ruby: ret=li.each {|elem| elem.do_something}

4) yield (the 'round' wheels)

Ruby code for fibo series from Programming Ruby:The Pragmatic Programmer's Guide

def fibUpTo(max)
...i1, i2 = 1, 1
...while i1 <= max
......yield i1
......i1, i2 = i2, i1+i2
...end
end
fibUpTo(1000) { |f| print f, " " }

Python code for fibo series

def fibUpTo(max):
...i1,i2=1,1
...while i1<=max:
......yield i1
......i1,i2=i2,i1+i2
print [i for i in fibUpTo(1000)]

5) Syntax
Python: Indentation rules
Ruby: OO

6)Readability: --->depends on u

This (friendly???) war is certainly gonna continue, but its quite a learning experience and has made me more passionate about Py!

More issues will be discussed and more rants will be thrown around.....watchout!

4 comments:

Maverick said...

Yea..i agree with most of ur blog, except the code blocks and yield...u aint done justice to it
in other words, py yields can only be used with/for generators, whereas ruby yields are a lot more generic.
anyways, wat i feel is...
"A language that doesn’t affect the way you think about programming is not worth knowing — Alan Perlis" (in one of Paul Graham's essays).
im pretty sure most of u will agree!

Hrishikesh said...

Plus Py yeilds require an argument. Ry yeilds can work independent of them. They are built into the language, rather than an addition to it.

Hrishikesh said...

Gaaah... Stupid spellings...

Read all yeilds in the above post as yield.

Gautam Arora said...

I am outta time to discuss this further due to recent engagements.... ;)

All I can say is that I fought the battle and the war...

Hope you find peace in Ruby...Python owns me...and when I can find time(outta my busy schedule), i would like to dedicate it to working on some open src py project...