[Tutor] check for nested sequences & flatten

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 14 Feb 2002 09:00:19 +0100


On  0, kevin parks <kp87@lycos.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, [2], [3, [4]]])  yeilds: 3"""
> 	
> 	seq[:]
> 	depths = [0]
> 	for obj in seq:
> 		try:
> 			depths.append(isNested(obj))
> 		except:
> 			pass
> 	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 [0], and every recursion eventually returns that zero, and
the previous call appends it to its depths list; you need a +1 in there
somewhere :).

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:

import types

def is_nested(L):
   for item in L:
      is type(item) in (types.ListType, types.TupleType):
         return 1
   return 0