[Tutor] flatten a tuple

D-Man dsh8290@rit.edu
Wed, 18 Apr 2001 14:39:42 -0400


On Wed, Apr 18, 2001 at 10:58:42AM -0700, Sean 'Shaleh' Perry wrote:
| So I have a tuple:
| 
| ((0, 1, 2), (3,4,5), (6,7,8))
| 
| and I want to get:
| 
| (6,7,8,3,4,5,0,1,2)
| 
| i.e. reverse the container, then get the contents in order.
| 
| The tuple in question happens to be a 3x3, but this need not affect
| the answer.

Reversing is easy :

def reverse_tuple( t ) :
    l = list( t )
    l.reverse()
    return tuple( l )


maybe you could save (execution) time and leave it as a list?


import types

def flatten( coll ) :
    """
    Take a linear collection (currently only handles tuple and list
    properly) and return a tuple containing all the elements.  Any
    sub-tuple/list will be "flattened".
    """

    # the result, as a list
    res_l = []

    for item in col :
        # here is where Lisp is a bit better, or the new adapter stuff
        # would be _really_ useful
        #
        #
        # If the item is a list/tuple, recursively flatten it, then
        # add all that stuff to the result list.
        #
        # Otherwise it is an "atom" (see Lisp for a definition),
        # append it to the result list.
        #
        if type( item ) == types.ListType or type( item ) ==
            types.TupleType :
            res_l.extend( flatten( item ) )
        else :
            res_l.append( item )

    return tuple( res_l )




print flatten( reverse( ((0, 1, 2), (3,4,5), (6,7,8)) ) )


Double check, then thoroughly test this :-).

-D