Problem Description:
Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.
Solution:
def plusMinus(arr):
n = len(arr) # Total number of elements
pos = sum(1 for x in arr if x > 0) # Count positives
neg = sum(1 for x in arr if x < 0) # Count negatives
zero = n - pos - neg # Remaining are zeros
# Print ratios with 6 decimal places
print(f"{pos / n:.6f}")
print(f"{neg / n:.6f}")
print(f"{zero / n:.6f}")
# Example usage:
arr = list(map(int, input("Enter the elements of the array separated by space: ").split()))
plusMinus(arr)
Example Run :
Input:
-4 3 -9 0 4 1
Output:
0.500000
0.333333
0.166667
How the Solution Works
1.Count the elements by type
Go through the array and count how many numbers are:
- Positive (greater than 0)
- Negative (less than 0)
- Zero
2.Calculate ratios
Divide each count by the total number of elements in the array.
- Positive ratio = (number of positive elements) ÷ (total elements)
- Negative ratio = (number of negative elements) ÷ (total elements)
- Zero ratio = (number of zeros) ÷ (total elements)
3.Format the output
Print each ratio on a new line with exactly 6 decimal places.