LoginSignup
1
0

More than 3 years have passed since last update.

超小ネタ 引数に渡した複数の数値が0を除き同じ符号かを判定する

Last updated at Posted at 2019-06-27

コード

def is_same_sign(*numbers) -> bool:
    return len({x > 0 for x in numbers if x != 0}) <= 1

テスト

assert is_same_sign(*[1, 5, 0])
assert not is_same_sign(*[-1, 5, 0])
assert is_same_sign(*[0, 0, 0, 0])

解説

関数is_same_signは、set内包表記を用いて、
- 引数の中で0でない要素のみを絞り込み、
- 0より大でTrue
- 0より小ならFalse

とするboolsetを作る。

このset
- set(): 長さ0の空set
- {True}{False}: 長さ1のset
- {True, False}{False, True}: 長さ2のset
となり、全て符号が同じ = setの要素数が0または1 = 要素数が1以下ということができる。

以上。

1
0
1

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
1
0