論理演算を用いた計算のまとめ

0 または 1 の整数 A, B, C, D が与えられます。 以下の式を計算した結果を出力してください。

 

 

#入力

A B C D

 

 

#出力

問題文の式の計算結果を 0 または 1 で出力してください。末尾に改行を入れ、余計な文字、空行を含んではいけません。

 

 

#コード

a,b,c,d = map(int,input().split())

def nRes(x):
    y = int(not(x))    
    return(y)

ans = (nRes*1 | nRes(c)) ^ d)
print(ans)

 

 

#参考

Python3 の場合 ( 1 )

a, b, c, d = map(int, input().split())
print(int(not((not (a) and not (b)) or not (c)) ^ d))
  • Python でも同じように正解することができます。しかし、 not 演算子は bool 型で計算されるため、 int 型に変換する必要があります。

Python3 の場合 ( 2 )

a, b, c, d = map(int, input().split())
print(((a or b) and c) ^ d)
  • Python でド・モルガンの法則を用いた例です。こちらも簡潔な式となっています。

*1:nRes(a) & nRes(b