Daily Challenge: Calculate the ratios of array elements/Print the decimal value of it
TASK: Calculate the ratios of integers in an array that are positive, negative, and zero. Print the decimal value of each fraction on a new line with six places after the decimal.
Python:
def plusMinus(arr):
size = len(arr)
plus = [i for i in arr if i > 0]
minus = [i for i in arr if i < 0]
zero = [i for i in arr if i is 0]
print('{:.6g}'.format(len(plus) / size))
print('{:.6g}'.format(len(minus) / size))
print('{:.6g}'.format(len(zero) / size))
if __name__ == '__main__':
arr = [-4, 3, -9, 0, 4, 1]
plusMinus(arr)
Result:
0.5
0.333333
0.166667
Better code from a better coder:
def plusMinus(arr):
length = len(arr)
zero = arr.count(0) / length
positive = len([x for x in arr if x > 0]) / length
negative = 1 - zero - positive
print("{:.6f}\n{:.6f}\n{:.6f}\n".format(positive, negative, zero))
Reference: Plus Minus (Hackerrank)