[Tutor] check for nested sequences & flatten
Thu, 14 Feb 2002 09:00:19 +0100
On 0, kevin parks <email@example.com> wrote:
> # what's up with this ?
> def isNested(seq):
> """isNested: checks a list for nesting and if nested, exactly how deeply
> >>> isNested([1,2,3]) yeilds: 1
> >>> isNested([1, , [3, ]]) yeilds: 3"""
> depths = 
> for obj in seq:
> return max(tuple(depths))
First, the line 'seq[:]' does nothing. Oh wait - you use it to generate an
exception in case it's not possible. That makes the code more general than
your flatten() function, which only checked for ListType and TupleType. But
it also introduces a problem: for instance, if you feed it the string 'a',
then that is a sequence with one element - 'a'! The depth of the string is
infinite. If you only use it for real lists and tuples anyway, maybe it's
better to check for that.
Second, depths is , and every recursion eventually returns that zero, and
the previous call appends it to its depths list; you need a +1 in there
Thirdly, what you've written is a max_depth() function (if you add +1 to the
return call). A function that only calculates is_nested() is easier:
for item in L:
is type(item) in (types.ListType, types.TupleType):