Program to find sign of the product of an array using Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums. We have to find sign of the multiplication result of all elements present in the array.

So, if the input is like nums = [-2,3,6,-9,2,-4], then the output will be Negative, as the multiplication result is -2592

To solve this, we will follow these steps −

  • zeroes := 0,negatives := 0

  • for each i in nums, do

    • if i is same as 0, then

      • zeroes := zeroes + 1

    • if i < 0, then

      • negatives := negatives + 1

  • if zeroes > 0 , then

    • return "Zero"

  • otherwise when negatives mod 2 is same as 0, then

    • return "Positive"

  • otherwise,

    • return "Negative"

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums):
   zeroes,negatives = 0,0
   for i in nums:
      if i == 0:
         zeroes+=1
      if i < 0:
         negatives+=1
      if zeroes > 0:
         return "Zero"
      elif negatives % 2 == 0:
         return "Positive"
      else:
   return "Negative"
nums = [-2,3,6,-9,2,-4]
print(solve(nums))

Input

[-2,3,6,-9,2,-4]

Output

Negative
raja
Published on 27-May-2021 15:03:53
Advertisements