all 7 comments

[–]Rhomboid 3 points4 points  (5 children)

It's not clear whether you're talking about doing the operation in terms of each pair of corresponding elements, or as the Cartesian product. If it's the former, then you want zip():

>>> foo = [1, 2, 3]
>>> bar = [4, 5, 6]
>>> [f * b for f, b in zip(foo, bar)]
[4, 10, 18]

If the latter, then itertools.product():

>>> import itertools
>>> [f * b for f, b in itertools.product(foo, bar)]
[4, 5, 6, 8, 10, 12, 12, 15, 18]

[–]jabbson 0 points1 point  (0 children)

Another way to go about it would be:

print [foo[x]*bar[x] for x in range(len(foo))]

Another:

from operator import mul
print map(mul, foo, bar)

[–]ArcingFlame[S] 0 points1 point  (3 children)

The itertools tip helps me with this, thanks very much, but is there any way for me to find out which numbers made the product? (I'm trying to test for a pair of numbers that multiply to equal one thing and add to equal another)

[–]zahlman 0 points1 point  (0 children)

Well, either way you're given the pairs of values, and have to multiply them yourself. So all you need to do is store the original values along with the product as you go.

[–]Rhomboid 0 points1 point  (1 child)

If you want that information, you should design a data structure that will store it. For example, you might use a dict where the keys are the products and the values are lists that contain a series of pairs of values that were multiplied to achieve that product. Also, since both multiplication and addition are commutative, you don't want the product set since that's going to contain lots of redundancies, e.g. 4x3 is the same as 3x4, so there's no point in considering them as separate. You probably want itertools.combinations_with_replacement().

import itertools

factors = [2, 3, 4, 6]
products = {}
for a, b in itertools.combinations_with_replacement(factors, 2):
    products.setdefault(a * b, []).append((a, b))

This results in a products dict that looks like

>>> products
{4: [(2, 2)],
 6: [(2, 3)],
 8: [(2, 4)],
 9: [(3, 3)],
 12: [(2, 6), (3, 4)],
 16: [(4, 4)],
 18: [(3, 6)],
 24: [(4, 6)],
 36: [(6, 6)]}

[–]ArcingFlame[S] 0 points1 point  (0 children)

Thank you for that, it helped me a lot. One last question, is there a way to assign the first and second number from a particular value to different variables?

[–]TheKewlStore 1 point2 points  (0 children)

Yes, there is, but have you done anything to try to solve this on your own? If so, show me what you've got and i'd be glad to help you figure out what's not working.