[Tutor] check for nested sequences & flatten [functional
Thu, 14 Feb 2002 00:24:54 -0800 (PST)
On Thu, 14 Feb 2002, Remco Gerlich wrote:
> import types
> def is_nested(L):
> for item in L:
> is type(item) in (types.ListType, types.TupleType):
> return 1
> return 0
We can pretend to be pathologically addicted to functional programming,
and see what is_nested() might look like to such warped individuals.
Here's a function that checks to see if a certain condition is true
anywhere in the list:
def any(condition_function, seq):
"""Returns 1 if any element in our sequence 'seq'
responds favorably to our 'condition_function'."""
for element in seq:
Why would anyone want to write something so weird? One reason is because
any() gives us a nice way of writing certain tests over any sequence:
>>> def isEven(x): return x % 2 == 0
>>> any(isEven, [1, 3, 5, 8, 9])
>>> any(lambda n: not isEven(n), [2, 4, 6, 8])
>>> any(lambda ch: ch in 'aeiou', 'zzzzzz')
>>> any(lambda ch: ch in 'aeiou', 'kazzam')
and I think that's quite neat to be able to test sequences out like that,
without even having to write a loop.
Once we have any(), is_nested() is a snap:
def isList(x): return type(x) in (types.ListType,
return any(isList, L)
Hope this helps!