[Tutor] check for nested sequences & flatten [functional programming/lambda]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
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:
        if condition_function(element):
            return 1
    return 0
###


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])
1
>>> any(lambda n: not isEven(n), [2, 4, 6, 8])
0
>>> any(lambda ch: ch in 'aeiou', 'zzzzzz')
0
>>> any(lambda ch: ch in 'aeiou', 'kazzam')
1
###

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 is_nested(L):
    def isList(x): return type(x) in (types.ListType,
                                      types.TupleType)
    return any(isList, L)
###



Hope this helps!