[Tutor] Flatten

C Smith smichr at hotmail.com
Mon Apr 11 11:12:30 CEST 2005


Sorry for the delay in answering.

Bill Mill wrote:
[cut]
> 1) you should special-case dictionaries: > >> x = [1, 2, [3, 4, 5, 
> [[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}] > >> flatten(x) > >> x 
> [1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test']
>
OK, now it only handles lists and tuples
> 2) What's different about your flatten than those ASPN entries? Just
> that it flattens in-place? I see a general-purpose flattener and a
> flattening generator.

The flatten procedure by Ganel does excessive work, it appears, by 
doing one level of flattening per pass through the entire list. Initial 
non-iterable items are rechecked as long as any iterables remain in the 
list. It is also not an "in-place" routine.

The one by Rodrigues and the one by Rol is recursive (and the one by 
Yoo is admittedly complicated).

The one I presented is essentially the same as Fletcher's.  Fletcher's 
does not actually run through all indices as I thought: as soon as it 
steps on an out-of-range index it exits. Fletcher's routine is a 
non-recursive version that runs in place that can be recommended if 
recursion is a problem.

I'll add a note to the ASPN pages.

/c



More information about the Tutor mailing list