Home > Back-end >  Operation on each possible pair of items in the list
Operation on each possible pair of items in the list

Time:02-04

I want to collect the values of the product of each pair in a list of numbers.

This works fine with smaller numbers, but not with larger ones. How can I optimize my solution?

#will work fine with min = 10 & max = 99
#but not with these values under
min = 1000
max = 9999
seq = range(min, max   1)
products = set()
for i in seq:
    for j in seq:
        p = i * j
        products.add(p)

CodePudding user response:

You can use numpy to take the outer product and then take the unique values.

min_num = 1000
max_num = 9999

numbers = np.arange(min_num, max_num 1)

products = np.unique(np.outer(numbers, numbers))

CodePudding user response:

You can build a set directly with a comprehension. To optimize, only compute each product once by multiplying numbers with subsequent ones and themselves rather than every inverted pairs (which only wastes time producing duplicate values):

lo = 1000
hi = 9999

prods = {i*j for i in range(lo,hi 1) for j in range(i,hi 1)}

print(len(prods)) # 20789643

CodePudding user response:

Nested list comprehension should be faster:

products = [i*j for i in seq for j in seq]
  • Related