I have decided to update the scope to take a list and the number of terms that you wish to find the maximum product of.
This should be a more general solution to the problem.
I have included error handling for if the number of terms exceeds the length of sequence.
import numpy import itertools def maximum_product_of_three(sequence, terms): max = 0 combos = itertools.combinations(sequence, terms) for set in combos: if numpy.prod(set) > max: max = numpy.prod(set) combo = set return combo, max
def maximum_product_of_three(a):a.sort()return max(a[0]*a[1]*a[-1], a[-3]*a[-2]*a[-1])- import numpy
- import itertools
- def maximum_product_of_three(sequence, terms):
- max = 0
- combos = itertools.combinations(sequence, terms)
- for set in combos:
- if numpy.prod(set) > max:
- max = numpy.prod(set)
- combo = set
- return combo, max
test.assert_equals(maximum_product_of_three([3, -4, 8, -4],2), ((3,8),(3 * 8))) # test.assert_equals(maximum_product_of_three([4, 3, 5, 2]), 3 * 4 * 5) # test.assert_equals(maximum_product_of_three([3, 9, 13]), 3 * 9 * 13) # test.assert_equals(maximum_product_of_three([11, -2, -7, 8, 2]), 2 * 8 * 11) # test.assert_equals(maximum_product_of_three([-4, -2, -9, -3, -5]), -2 * -3 * -4) # test.assert_equals(maximum_product_of_three([-4, -2, -9, 1, -3, -5]), -5 * -9 * 1) # test.assert_equals(maximum_product_of_three([-4, -2, -9, 0, -3, -5]), 0)
test.assert_equals(maximum_product_of_three([2, -4, 8, -4]), -4 * -4 * 8)test.assert_equals(maximum_product_of_three([4, 3, 5, 2]), 3 * 4 * 5)test.assert_equals(maximum_product_of_three([3, 9, 13]), 3 * 9 * 13)test.assert_equals(maximum_product_of_three([11, -2, -7, 8, 2]), 2 * 8 * 11)test.assert_equals(maximum_product_of_three([-4, -2, -9, -3, -5]), -2 * -3 * -4)test.assert_equals(maximum_product_of_three([-4, -2, -9, 1, -3, -5]), -5 * -9 * 1)test.assert_equals(maximum_product_of_three([-4, -2, -9, 0, -3, -5]), 0)- test.assert_equals(maximum_product_of_three([3, -4, 8, -4],2), ((3,8),(3 * 8)))
- # test.assert_equals(maximum_product_of_three([4, 3, 5, 2]), 3 * 4 * 5)
- # test.assert_equals(maximum_product_of_three([3, 9, 13]), 3 * 9 * 13)
- # test.assert_equals(maximum_product_of_three([11, -2, -7, 8, 2]), 2 * 8 * 11)
- # test.assert_equals(maximum_product_of_three([-4, -2, -9, -3, -5]), -2 * -3 * -4)
- # test.assert_equals(maximum_product_of_three([-4, -2, -9, 1, -3, -5]), -5 * -9 * 1)
- # test.assert_equals(maximum_product_of_three([-4, -2, -9, 0, -3, -5]), 0)