Self function
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue May 5 03:51:19 EDT 2009
On Mon, 04 May 2009 23:09:25 -0700, Carl Banks wrote:
> On May 4, 8:22 pm, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
>> On Mon, 04 May 2009 15:51:15 -0700, Carl Banks wrote:
>> > All
>> > recursion does it make what you're doing a lot less readable for
>> > almost all programmers.
>>
>> What nonsense.
>
> It's not nonsense for a singly-linked list.
def ivisit(node):
print node
while node and node.link is not None:
node = node.link
print node
def rvisit(node):
print node
if node and node.link is not None:
rvisit(node.link)
If there are programmers who find rvisit "a lot less readable" than
ivisit, then in my arrogant opinion they should consider a change of
profession.
> I don't need to be taught
> the benefit of recursion, but whenever interation is suitable for an
> algorithm/data structure, as it is with singly-linked lists, then it is
> the more readable and more preferrable choice, especially in Python.
Most (all?) recursive algorithms can be re-written as iteration. For many
recursive algorithms (but not all) the cost for doing so is to simulate
recursion yourself by managing your own stack. By making such an
absolutist claim, you're claiming that it is "more readable" and "more
preferable" to manage your own stack than to let the compiler do so.
That's clearly nonsense.
Whenever iteration gives a simpler and more readable algorithm than
recursion, then it should be preferred on account of being simpler and
more readable. That's not just a no-brainer, it's a tautology. "Whenever
iteration is simpler, it's simpler." But that's a far cry from what you
said: that recursion, as a general technique, is "a lot less readable"
for "almost all" programmers.
> In Python the One Obvious Way is iteration when possible, recursion when
> necessary.
There's nothing "obvious" about solving the 8 Queens problem using
iteration. Or walking a binary tree. Or generating all the permutations
of a list.
But don't just tell me that recursion isn't Pythonic. Tell Guido:
http://www.python.org/doc/essays/graphs.html
I quote:
"These [recursive] functions are about as simple as they get. Yet, they
are nearly optimal (for code written in Python)."
--
Steven
More information about the Python-list
mailing list