Search code examples
pythonpython-3.xmathematical-optimization

max possible product of a list with any elements


I have made below function for the same. but it is failing a particular test case I cant know what the input is. What would be a possible input list this function is failing to return max product? The input will be list of numbers and output should be the max possible product by taking any numbers from list so that product would be max.

def max_prod(xs):
  negl = []
  nego = []
  pos = []
  prod = 1
  # if any positive integer greater than 1, then dont need to consider negative integers between -1 and 0
  if any(i for i in xs if i >= 1):
    for i in xs :
      if i <= -1 : nego.append(i)
      elif i > 1 : pos.append(i)
    if  len(nego) % 2 == 1 :
      nego.remove(max(nego))
    for  i in pos : prod = prod * i
    for j in nego : prod = prod * j
    return str(prod)
  
  #if there is no positive integer greater than or equal to 1, 
  else :
    l = []
    for i in xs :
      if i > 0 : pos.append(i)
    if len(pos) != 0 : l.append(max(pos))
    for i in xs :
      if i <= -1  :
        nego.append(i)
      elif i < 0  and i > -1 :
        negl.append(i)
    # if there is only one negative integer lesser than -1
    if len(nego) == 1 :
      if len(negl) == 0:
        return str(0)
      else :
        l.append((nego[0] * min(negl)))
        return str(max(l))
    # if multiple integers lesser than -1
    else :
      if len(nego) >= 1 and len(nego) % 2 == 1 :
        nego.remove(max(nego))
      for  i in nego : prod = prod * i
      return str(prod)

Solution

  • Post request corner cases where the posted code doesn't work.

    Code provides incorrect answers for single negative numbers.

    Examples:

    print(max_prod([0]))
    # Output: 1
    

    The answer should be 0

    Simple fix would be to add condition:

    if xs == [0]:
        return 0
    

    Simpler Code

    from math import prod
    
    def max_prod(xs):
      pos = [i for i in xs if i > 0]
      neg = [i for i in xs if i < 0]
    
      if len(neg) % 2:
        neg.remove(max(neg))  
        
      if len(pos) > 0 or len(neg) > 0:
        return str(prod(pos) * prod(neg))
    
      return "0"
    

    Tests

    for xs in [[], [0], [2], [-2], [2, 3], [0, 2, 3], 
               [-2, -3], [-2, -3, -4], [2, 0, -2, -3], 
               [2, 0, -2, -3, -1]]:
      print(f'{xs} max-> {max_prod(xs)}')
    

    Output

    [] max-> 0
    [0] max-> 0
    [2] max-> 2
    [-2] max-> 0
    [2, 3] max-> 6
    [0, 2, 3] max-> 6
    [-2, -3] max-> 6
    [-2, -3, -4] max-> 12
    [2, 0, -2, -3] max-> 12
    [2, 0, -2, -3, -1] max-> 12