
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sign of the Product of an Array Using Python
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
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
Advertisements