Javatpoint Logo
Javatpoint Logo

Python Program to return the Sign of the product of an Array

In this tutorial, we will write the Python program to which returns the Sign of an array's product. It is an easy leetcode problem and can be asked in technical interviews. Let's understand the problem statement.

Problem Statement

Example - 1

Input: nums = [-1,-2,-3,-4, 3, 2, 1]

Output: 1

Example - 2

Input: nums = [1, 5, 0, 2, -3]

Output: 0

Explanation -

Here, we need to calculate the product of all list values; if it returns a positive integer, the sign will be 1. If it returns a negative value, the sign will be -1, else returns 0.

The product of the above list is 144, which is a positive integer; hence the output is 1.

Constraints -

We need to define a separate function that returns the following result.

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

Let' write a Python program to solve this problem.

Solution

Let's understand the below solution.

Output 1:

1

nums = [-1, 1, -1, 1, -1]

Output 2:

-1

Explanation -

In the prodSign() function, we defined the prod variable to store the product of the variable. The for loop iterate each value and updates the prod value. In the first iteration, i is -1, and prod is 1, so the product will be -1. Now, -1 is assigned to the prod variable. In the second iteration, i is -2, and prod is -1; hence the product will be 2. Once we get the final product, call the signfun() and return the Sign according to the result.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA