0
1

More than 3 years have passed since last update.

[デイリーコーディング]リスト内の数値の正の数、負の数、ゼロそれぞれの割合を表示する

Last updated at Posted at 2021-02-25

今日の問題: リスト内に入っている整数の正の数、負の数、ゼロそれぞれ合計し、リスト全体から見た各割合を出せ(小数点6桁四捨五入)

回答
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)
結果
0.5
0.333333
0.166667

ベターな回答:


def plusMinus(arr):
  positive = sum(x > 0 for x in arr) / len(arr)
  negative = sum(x < 0 for x in arr) / len(arr)
  zero = sum(x == 0 for x in arr) / len(arr)

  print("{0:.6f}".format(positive), 
        "{0:.6f}".format(negative), "{0:.6f}".format(zero), sep="\n")

参照: Plus Minus (Hackerrank)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1