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

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.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/courses/263194.html

(0)
上一篇 2022年5月30日 17:34
下一篇 2022年5月30日 17:34

相关推荐

发表回复

登录后才能评论