규도자 개발 블로그

[해커랭크(Hackerrank)/Problem Solving/파이썬3(python3)] Plus Minus 본문

알고리즘/풀이

[해커랭크(Hackerrank)/Problem Solving/파이썬3(python3)] Plus Minus

규도자 (gyudoza) 2019. 3. 9. 15:24

Given an array of integers, calculate the fractions of its elements that are positivenegative, and are zeros. 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  are acceptable.

For example, given the array  there are  elements, two positive, two negative and one zero. Their ratios would be  and . It should be printed as

0.400000
0.400000
0.200000

Function Description

Complete the plusMinus function in the editor below. It should print out the ratio of positive, negative and zero items in the array, each on a separate line rounded to six decimals.

plusMinus has the following parameter(s):

  • arr: an array of integers

Input Format

The first line contains an integer, , denoting the size of the array. 
The second line contains  space-separated integers describing an array of numbers .

Constraints

 

Output Format

You must print the following  lines:

  1. A decimal representing of the fraction of positive numbers in the array compared to its size.
  2. A decimal representing of the fraction of negative numbers in the array compared to its size.
  3. A decimal representing of the fraction of zeros in the array compared to its size.

Sample Input

6
-4 3 -9 0 4 1         

Sample Output

0.500000
0.333333
0.166667

Explanation

There are  positive numbers,  negative numbers, and  zero in the array. 
The proportions of occurrence are positive: , negative:  and zeros: .

풀이

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the plusMinus function below.
def plusMinus(arr):
    list_size = len(arr)
    positive_counter = 0
    zero_counter = 0
    negative_counter = 0
    for number in arr:
        if(number > 0):
            positive_counter = positive_counter + 1
        elif(number == 0):
            zero_counter = zero_counter + 1
        elif(number < 0):
            negative_counter = negative_counter + 1
    print("{0:.6f}".format(positive_counter / list_size))
    print("{0:.6f}".format(negative_counter / list_size))
    print("{0:.6f}".format(zero_counter / list_size))
    

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

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

    plusMinus(arr)

설명

주어진 숫자들의 특성이 배열에서 차지하는 만큼의 비율을 소수점 6자리까지 표시하는 문제이다. 맨 위부터 차례대로 양수, 음수, 0이 배열에서 차지하는 비율을 출력한다. 이건 다른 문제와 달리 반환값으로 만드는게 아니라 바로 stdout으로 출력해야 하는 문제여서 조금 해멨다. hackerrank문제를 푸는 사람이 있다면 반환값 검사 문제인지 stdout을 검사하는 문제인지 주의해야겠다.


Comments