Last active
September 19, 2020 16:48
-
-
Save willy-r/8354a5739a70f749836b40076e19f2c3 to your computer and use it in GitHub Desktop.
Write a program that implements logic gates AND, OR, NOT, NAND, NOR, XOR, and XNOR.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def and_gate(x, y): | |
"""The AND gate gives an output of 1 if both | |
the two inputs are 1, it gives 0 otherwise. | |
""" | |
if x == 1 and y == 1: | |
return 1 | |
return 0 | |
def or_gate(x, y): | |
"""The OR gate gives an output of 1 if either | |
of the two inputs are 1, it gives 0 otherwise. | |
""" | |
if x == 1 or y == 1: | |
return 1 | |
return 0 | |
def not_gate(x): | |
"""It acts as an inverter. It takes only one input. | |
If the input is given as 1, it will invert the result as 0 and vice-versa. | |
""" | |
if x == 0: | |
return 1 | |
return 0 | |
def nand_gate(x, y): | |
"""The NAND gate gives an output of 0 if both | |
inputs are 1, it gives 1 otherwise. | |
""" | |
if x == 1 and y == 1: | |
return 0 | |
return 1 | |
def nor_gate(x, y): | |
"""The NOR gate gives an output of 1 if both | |
inputs are 0, it gives 0 otherwise. | |
""" | |
if x == 0 and y == 0: | |
return 1 | |
return 0 | |
def xor_gate(x, y): | |
"""The XOR gate gives an output of 1 if either both | |
inputs are different, it gives 0 if they are the same. | |
""" | |
if x != y: | |
return 1 | |
return 0 | |
def xnor_gate(x, y): | |
"""The XNOR gate gives an output of 1 if both | |
inputs are the same and 0 if both are different. | |
""" | |
if x == y: | |
return 1 | |
return 0 | |
def logic_gates(gate_type, x, y=0): | |
"""Write a program that implements logic gates | |
AND, OR, NOT, NAND, NOR, XOR, and XNOR. | |
""" | |
gate_type = gate_type.upper() | |
if gate_type not in ['AND', 'OR', 'NOT', 'NAND', 'NOR', 'XOR', 'XNOR']: | |
return 'Invalid gate type' | |
if gate_type == 'AND': | |
return and_gate(x, y) | |
if gate_type == 'OR': | |
return or_gate(x, y) | |
if gate_type == 'NOT': | |
return not_gate(x) | |
if gate_type == 'NAND': | |
return nand_gate(x, y) | |
if gate_type == 'NOR': | |
return nor_gate(x, y) | |
if gate_type == 'XOR': | |
return xor_gate(x, y) | |
if gate_type == 'XNOR': | |
return xnor_gate(x, y) | |
if __name__ == '__main__': | |
assert logic_gate('ELSE', 1, 1) == 'Invalid gate type' | |
assert logic_gate('AND', 1, 1) == 1 | |
assert logic_gate('OR', 0, 0) == 0 | |
assert logic_gate('NOT', 1) == 0 | |
assert logic_gate('NAND', 1, 0) == 1 | |
assert logic_gate('NOR', 0, 0) == 1 | |
assert logic_gate('XOR', 3, 3) == 0 | |
assert logic_gate('XNOR', 1, 1) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment