새소식

Programming/1 Day 1 Commit

[HackerRank] PlusMinus (python)

  • -

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  places after the decimal.

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.

Example

There are  elements, two positive, two negative and one zero. Their ratios are ,  and . Results are printed as:

0.400000
0.400000
0.200000

Function Description

Complete the plusMinus function in the editor below.

plusMinus has the following parameter(s):

  • int arr[n]: an array of integers

Print
Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with  digits after the decimal. The function should not return a value.

Input Format

The first line contains an integer, , the size of the array.
The second line contains  space-separated integers that describe .

Constraints


Output Format

Print the following  lines, each to  decimals:

  1. proportion of positive values
  2. proportion of negative values
  3. proportion of zeros

Sample Input

STDIN           Function
-----           --------
6               arr[] size n = 6
-4 3 -9 0 4 1   arr = [-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: .

First Try : RunTime error

input array의 양수, 음수, 0의 개수를 판별하여 이를 array 속의 개수로 나눠 비율을 구하면 되는 비교적 간단한 문제. 

파이썬으로 쉽게 풀 수 있다고 생각했으나 문제에 봉착하였다. 

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#

def plusMinus(arr):
    # Write your code here
    plus = 0
    minus = 0
    zero = 0
    for i in len(arr):
        if arr[i] > 0: plus += 1
        if arr[i] == 0: zero += 1
        if arr[i] < 0: minus += 1
    return plus/len(arr), minus/len(arr), zero/len(arr)

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

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

    plusMinus(arr)

Second Try: Success but look diff

반복문에서 range부분을 할당해주지 않았으니 돌아갈 리가 없다! (아직도 적응되지 않은 파이썬 문법...)

함수를 호풀할때 리턴값을 지정해줄 필요가 없으므로 그냥 print로 값을 불러주면 된다. 

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#

def plusMinus(arr):
    # Write your code here
    plus = 0
    minus = 0
    zero = 0
    for i in range(len(arr)):
        if arr[i] > 0: plus += 1
        if arr[i] == 0: zero += 1
        if arr[i] < 0: minus += 1
    print(plus/len(arr))
    print(minus/len(arr))
    print(zero/len(arr))

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

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

    plusMinus(arr)

 

[Answer] output 소수점 아래 개수가 맞지 않는 모습

Solution

소수점 뒤의 개수를 맞춰주기 위해서는 포맷을 맞춰주면 된다. 

가독성을 위해서 코드가 길어지더라도 각각을 선언한뒤 만들어주었다. 

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#

def plusMinus(arr):
    # Write your code here
    plus = 0
    minus = 0
    zero = 0
    for i in range(len(arr)):
        if arr[i] > 0: plus += 1
        if arr[i] == 0: zero += 1
        if arr[i] < 0: minus += 1
    len_arr = len(arr)
    minus_fraction = float(minus)/float(len_arr)
    plus_fraction = float(plus)/float(len_arr)
    zero_fraction = float(zero)/float(len_arr)
    print("{:.5f}".format(plus_fraction))
    print("{:.5f}".format(minus_fraction))
    print("{:.5f}".format(zero_fraction))
    

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

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

    plusMinus(arr)

 

[Success] 완성된 모습

 

Github Link

 

GitHub - Park-Minjoo/CODINGINTERVIEW_PRACTICE: 1 Day 1 Problem since 2022.4.7

1 Day 1 Problem since 2022.4.7. Contribute to Park-Minjoo/CODINGINTERVIEW_PRACTICE development by creating an account on GitHub.

github.com

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.