コード
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
とするbool
のset
を作る。
このset
は
- set()
: 長さ0の空set
- {True}
か{False}
: 長さ1のset
- {True, False}
か{False, True}
: 長さ2のset
となり、全て符号が同じ = set
の要素数が0または1 = 要素数が1以下ということができる。
以上。