HackerRank Plus Minus ~ no response on stdout ~

Question:

Can someone please explain why hackerrank does not accept this code for python?

def plusMinus(arr):
    positive = "{0:.6f}".format(sum(1 for i in arr if i > 0) / len(arr))
    negative = "{0:.6f}".format(sum(1 for i in arr if i < 0) / len(arr))
    zero = "{0:.6f}".format(sum(1 for i in arr if i == 0) / len(arr))
    return "n".join([positive, negative, zero])

It gives me this error: ~ no response on stdout ~

Asked By: Zeke

||

Answers:

You will notice that on HackerRank your function is called without doing anything with the return value. The template code looks like this:

if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

Moreover, the description says:

Print the decimal value of each fraction on a new line.

So you should print the result. And since your code doesn’t print anything, the error message is what could be expected.

Instead of return, do:

print("n".join([positive, negative, zero]))
Answered By: trincot

btw … I know it’s quite old question, and You were asking why it’s not working, but I would like to highlight that here You are looping 3 times,
when You could do it only once.. and You are working on floats when it was mentioned to work on decimal… I would like to invite You to take a look how to work with them (with Decimal):

from decimal import Decimal, ROUND_HALF_DOWN
    

def plusMinus(arr):
    positive = 0
    negative = 0
    zero = 0
    size = len(arr)
    for i in range(0, size):
        if arr[i] > 0:
            positive += 1
        elif arr[i] < 0:
            negative += 1
        else:
            zero += 1

    prec = '.000001'

    positive = Decimal(positive) / Decimal(size)
    print(Decimal(positive).quantize(Decimal(prec), rounding=ROUND_HALF_DOWN))
    
    negative = Decimal(negative) / Decimal(size)
    print(Decimal(negative).quantize(Decimal(prec), rounding=ROUND_HALF_DOWN))
    
    zero = Decimal(zero) / Decimal(size)
    print(Decimal(zero).quantize(Decimal(prec), rounding=ROUND_HALF_DOWN))
Answered By: Leszek Kolacz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.