Plus Minus

Plus Minus

Plus Minus:

Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.

Note:

This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to (\(10^{4})\) are acceptable.

Input Format

The first line contains a single integer, N , denoting the size of the array. The second line contains N space-separated integers describing an array of numbers (\( a_0,a_1,a_2….a_n-1 \))

Output Format

You must print the following 3 lines:

  1. A decimal representing of the fraction of positive numbers in the array.
  2. A decimal representing of the fraction of negative numbers in the array.
  3. A decimal representing of the fraction of zeroes in the array.
Sample Input
6

-4 3 -9 0 4 1         

Sample Output
0.500000
0.333333
0.166667

Explanation

There are 3 positive numbers, 2 negative numbers, and 1 zero in the array. The respective fractions of positive numbers, negative numbers and zeroes are \( 3/6 \)=0.500000 , \( 2/6 \)=0.333333 and \( 1/6 \)=1.66667 , respectively.

Solution

Python


#!/bin/python

import sys


n = float(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
countNegative=0
countPositive=0
countZero=0
if((len(arr))==n):
    for i in (arr):
        if((int(i))>0):
            countPositive=countPositive+1
        elif((int(i))<0):
            countNegative=countNegative+1
        else:
            countZero=countZero +1

positive = float(countPositive/n)
negative = float(countNegative/n)
zero= float(countZero/n)

print (positive)
print negative
print zero

Bash


#!/bin/sh
read N
read array
array=( `echo ${array[@]}` )

p=0
n=0
z=0

for (( i = 0; i < N; i++ )); do
b=${array[$i]}

if [ $b -lt 0 ]; then
p=$(($p+1))
elif [ $b -gt 0 ]; then
n=$(($n+1))
else
z=$(($z+1))
fi
done

echo "$n/$N" | bc -l
echo "$p/$N" | bc -l
echo "$z/$N" | bc -l



comments powered by Disqus