Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them? Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them? python-3.x python-3.x

Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?


First, given the list and the index range, we can get the sublist A[i : j + 1]

[66, 77, 88]

For positive integers a and b, a * b is no less than a or b. So you don't need to do multiplying, it's not possible that multiplying of two or more elements has a smaller result. The minimum of this list is the minimum of all the multiplying results.

So the result is:

min(A[i : j + 1])


For generating the sublists, it is as simple as two nested for loops in a list comprehension:

def sublists(l,i,j):    return [l[m:n+1] for m in range(i,j+1) for n in range(m,j+1)]

example:

>>> sublists(A,2,4)[[66], [66, 77], [66, 77, 88], [77], [77, 88], [88]]

For finding the minimum product:

>>> min(map(prod, sublists(A,2,4)))66

(you import prod from numpy, or define it as def prod(x): return reduce(lambda i,j:i*j,x))


The accepted answer is correct for all positive ints as you cannot multiply the smallest element by any number and get a smaller result. It might make more sense if you were getting all the slices greater than length 1.

If you were going to calculate it then you could use itertools.islice to get each slice and get the min using a generator expression:

from itertools import islicefrom operator import mulprint(min(reduce(mul, islice(A, n, k + 1), 1)          for n in range(i, j + 1) for k in range(n, j + 1)))66

If for i = 0 and j = 4 you considered (44, 55, 66, 88) a legitimate slice then you would need to use itertools.combinations.