Multiply a tuple by a constant

J

Jay Davis

I often need to multiply a tuple by a
constant and the methods I use now are
not very pretty. The idea is to get a
new tuple that is some factor times the
start tuple, like 'newtup = .5 * oldtup'.

Is there a slick way to do this?
 
P

Peter Otten

Jay said:
I often need to multiply a tuple by a
constant and the methods I use now are
not very pretty. The idea is to get a
new tuple that is some factor times the
start tuple, like 'newtup = .5 * oldtup'.

Is there a slick way to do this?

Not really slick, but it works:
(5, 10, 15)

The space after the 5 is necessary. Alternatively, you can wrap the constant
in brackets:
(5, 10, 15)

Peter
 
J

Jeremy Sanders

I often need to multiply a tuple by a constant and the methods I use now
are not very pretty. The idea is to get a new tuple that is some factor
times the start tuple, like 'newtup = .5 * oldtup'.

Is there a slick way to do this?

I suggest looking at Numarray - a very convenient way of doing maths on
sets of numbers. Of course if you don't do very much it's not worth doing
this.

http://www.stsci.edu/resources/software_hardware/numarray

You can do things like:

import numarray

a = numarray.array( (1.,2.,5.,-46.) )
a *= 0.5
b = a + 3.4

Jeremy
 
L

Larry Bates

two ways:

t=(1,2,3)
newt=tuple(map(lambda x: x*0.5, t))

Note: apparently the map function is slated for deprication
(to be replaced by list comprehension)

List comprehension:

t=(1,2,3)
newt=tuple([x*0.5 for x in t])

-Larry Bates
 
M

Michele Simionato

I often need to multiply a tuple by a
constant and the methods I use now are
not very pretty. The idea is to get a
new tuple that is some factor times the
start tuple, like 'newtup = .5 * oldtup'.

Is there a slick way to do this?

You can always subclass tuple and redefine "*". Dunno if you would
consider it slick enough.

Michele
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,178
Messages
2,570,955
Members
47,509
Latest member
Jack116

Latest Threads

Top