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.
Example - 1
Input: nums = [-1,-2,-3,-4, 3, 2, 1]
Example - 2
Input: nums = [1, 5, 0, 2, -3]
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.
We need to define a separate function that returns the following result.
Let' write a Python program to solve this problem.
Let's understand the below solution.
nums = [-1, 1, -1, 1, -1]
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.
Next TopicFabric Module in Python
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week