dividing tuple elements with an int or float

castironpi at gmail.com castironpi at gmail.com
Fri Mar 21 14:14:42 CET 2008


On Mar 20, 9:28 am, "Jerry Hill" <malaclyp... at gmail.com> wrote:
> On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano
>
> <st... at remove-this-cybersource.com.au> wrote:
> > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote:
>
> >  > suppose
> >  > origsz=(400,300)
> >  > i want to divide the origsize by 2.5 so i can resize to (160,120)
>
> >  > scale=2.5
> >  > how can i get the newsz?
> >  > obviously origsz/2.5 won't work  ..
>
> >  newsz = (origsz[0]/scale, origsz[1]/scale)
>
> That works fine for a 2-tuple, but might get unwieldy for larger
> tuples, or if you don't know the length until runtime.  A more general
> solution might use a generator expression, like this:
>
> newsz = tuple(x/scale for x in origsz)

You want to perform a uniform call on the elements of a collection.
"Diagram A" appends 0 to every item of a list.

>>> y= [ [] for k in range( 10 ) ]
>>> def x( fun, *ar, **kw ):
...     def post( *xr, **xw ):
...             return fun( *(xr+ ar), **kw )
...     return post
...
>>> x( list.append, 0 )( y[0] )
>>> y
[[0], [], [], [], [], [], [], [], [], []]
>>> x( list.pop, 0 )( y[0] )
0
>>> y
[[], [], [], [], [], [], [], [], [], []]
>>> list( map( x( list.append, 0 ), y ) )
[None, None, None, None, None, None, None, None, None, None]
>>> y
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]

If the elements are immutable,

>>> y= [ () for k in range( 10 ) ]
>>> list( map( x( tuple.__add__, ( 0, ) ), y ) )
[(0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,)]

you get your new list from map.  Here it is with integer elements:

>>> y= ( 300, 400 )
>>> tuple( map( x( int.__add__, 1, ), y ) )
(301, 401)

--You could spell the call like this:
latemap( y, int.__add__, 1 )

With mul:

>>> tuple( map( x( int.__mul__, 2, ), y ) )
(600, 800)

It's like partial, but the argument addition is commuted.  The key is
that 'y' is going in the first slot, as 'self'.  It's not clear that
argument addition commution applies (matches, is correct, generalizes
with right meaning): you just want the first parameter to come from a
separate call.  Other uses cases of the generalizer might not align.
+ a fraction on 'x'.

Floats get harder, since you're looking at composition.

>>> tuple( map( compose( float, x( float.__mul__, 1/ 2.5 ) ), y ) )
(120.0, 160.0) # (160, 120)

+1 compose.

def compose( *f ):
    def post( *ar, **kw ):
            if len( f )> 1:
                    return f[0]( compose( *f[1:] )( *ar, **kw ) )
            return f[0]( *ar, **kw )
    return post




More information about the Python-list mailing list