[Tutor] recursivity and lists

Alan Gauld alan.gauld at btinternet.com
Fri Mar 4 14:14:19 EST 2016


On 04/03/16 15:00, Gaston wrote:

> Both work but I am not satisfied. Is there not a method that could do 
> the job of '+' operator (namely concatenate in a copy)?

Why would you want a method? An operator is a perfectly legitimate
feature and is at least as readable as a method. It is certainly no less
"functional". And of course, in Python + usually translates
to the __add__() method anyway.


As to how your initial function works can I suggest you sit down
with a pen and paper and work through the code iteration by
iteration. Start with 2 element lists and then try 3 elements.
By the time you've done that it should become clear.
Keep track of the contents of list1 and list2 and the
output for each call of the function.

Recursive can be a seductive technique but it can be a real
brain twister to work out and debug when things don;t go
as expected! The pen/paper manual approach is the most
reliable technique I've found.

Here is what I mean for a 2 element list pair:

list1		list2		f(list1,list2)
-----------------------------------------------
[1]		[2]		f([1],[]).append(2) # first call of f()
[1]		[]		[1].append(2) -> list1 becomes [1,2]
[1,2]           []              f([1,2],[])   # 2nd call of f() -> [1.2]

Now try that for 2 elements per list, then 3.
In effect you move elements from list 2 to list 1, or vice versa.
And you iterate over the list multiple times.
It's very inefficient as well as non intuitive.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list