hacker-rank | calculate ratios of positive, negative, and zero elements

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.


Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with an absolute error of up to 10^4 are acceptable.

Example
arr = [1, 1, 0, -1, -1]
There are n= 5 elements, two positive, two negative, and one zero. Their ratios are (2/5) = 0.400000 , (2/5) = 0.400000 and (1/5) = 0.200000. Results are printed as each in new lines:
0.400000
0.400000
0.200000

Coding language => Python
Coding logic => own logic

Solutions:

arr = [-4, 3, -9, 0, 4, 1]

 
# iterating each number in list
def findcount(numbers):
    pos_count, neg_count, zero_count = 0, 0, 0
    for num in numbers:
        # checking condition
        if num > 0:
            pos_count += 1
        elif num == 0:
            zero_count += 1
        elif num < 0:
            neg_count += 1
    return [pos_count, neg_count, zero_count]

def plusMinus(arr):
    l = len(arr)
    ratiolist = findcount(arr) 
    ratioOfPositive = ratiolist[0] / l
    ratioOfNegative = ratiolist[1] / l
    ratioOfZero = ratiolist[2] / l
    print(format(ratioOfPositive,'.6f' )+"\n"+ format(ratioOfNegative,'.6f' )+"\n"+ format(ratioOfZero,'.6f' ))

plusMinus(arr)

OUTPUT:
0.400000
0.400000
0.200000

NOTE: python print float digit with 6 decimal point
=> format(‘2′,’.6f’)
=> 2.000000

Leave a Reply

Your email address will not be published. Required fields are marked *