dividing tuple elements with an int or float

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 21 14:08:45 EDT 2008


On 21 mar, 10:14, castiro... at gmail.com wrote:
> On Mar 20, 9:28 am, "Jerry Hill" <malaclyp... at gmail.com> wrote:

> > 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] )

Sane programmers replace that crazyness with this code:

for x in collection:
  x.append(0)

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

Sane programmers replace that crazyness with this code:

tuple(x+1 for x in y)

> 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)

Sane programmers -like D'Aprano, Jerry Hill and me- replace that
crazyness with this code:

tuple(x/2.5 for x in y)

> 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

Sane programmers don't write such semi-functional things (unless it
helps expressing the problem in certain domains).
I now think that deprecating map, lambda & Co. was a good thing after
all.

--
Gabriel Genellina



More information about the Python-list mailing list