how to test for nesting inlist
cpsoct at my-deja.com
cpsoct at my-deja.com
Sun Jan 21 04:29:59 EST 2001
Thanks. and here i get a chance to learn something
recursion hurts my brain. map does everything but make coffee
doesn't it. It is amazing to me how many places map and filter
show up. i used map with None to lace lists last night. amazing
the things you can do in python.....
Thanks again
In article <94bvgu0kt4 at news2.newsguy.com>,
"Alex Martelli" <aleaxit at yahoo.com> wrote:
> <cpsoct at my-deja.com> wrote in message
news:94bhte$4iv$1 at nnrp1.deja.com...
> > Is there a way to test if a list in nested and if so how deep? so
that
> > you could type
> >
> > y=[1,2,3]
> > x=[1,[2,3]]
> >
> > howDeep(y)
> > howDeep(x)
> >
> > and it would return 0 (no nesting) for y and 1, for x (1 level of
> > nesting)
> >
> > Is this possible? It would seem really useful, but i don't see
anything
> > in the docs about how to do this.
>
> It's not a built-in (because its usefulness is not perceived as all
> that big...), but it's easy to code it yourself. Assuming you only
> care about lists and not tuples or other forms of 'nesting', e.g.:
>
> def howDeep(x):
> if type(x)!=type([]):
> return 0
> return 1+reduce(max,map(howDeep,x),0)
>
> Note that this returns 0 for a non-list, 1 for a list not containing
> any other lists, etc; this seems more natural to me than what
> you requested! Just change both occurrence of 0 into -1 to
> get exactly your specs.
>
> Of course, either or both of the recursion and the 'functional'
> approach can be removed if one so wishes, but I think this is
> the simplest approach to such a typical functional-programming
> question:-).
>
> Alex
>
>
Sent via Deja.com
http://www.deja.com/
More information about the Python-list
mailing list