Skip to content
44 changes: 44 additions & 0 deletions boolean_algebra/nand_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,50 @@ def nand_gate(input_1: int, input_2: int) -> int:
return int(not (input_1 and input_2))


def n_input_nand_gate(inputs: list[int]) -> int:
Comment thread
TTAAAN marked this conversation as resolved.
"""
Generalization of nand_gate() to support n inputs.
Calculate NAND of a list of input values.
Returns 0 only when all inputs are 1, 1 otherwise.

>>> n_input_nand_gate([1, 0, 1, 1, 0])
1
>>> n_input_nand_gate([1, 1, 1, 1, 1])
0
>>> n_input_nand_gate([0, 0, 0, 0, 0])
1
>>> n_input_nand_gate([1, 0, 0, 0, 0])
1

>>> n_input_nand_gate([1, 1])
0

>>> n_input_nand_gate([])
Traceback (most recent call last):
...
ValueError: Input list cannot be empty

>>> n_input_nand_gate([1])
Traceback (most recent call last):
...
ValueError: Input list must contain at least two elements

>>> n_input_nand_gate([2, 1])
Traceback (most recent call last):
...
ValueError: All inputs must be 0 or 1
"""

if len(inputs) == 0:
raise ValueError("Input list cannot be empty")
if len(inputs) < 2:
Comment thread
TTAAAN marked this conversation as resolved.
raise ValueError("Input list must contain at least two elements")
if not all(i in (0, 1) for i in inputs):
raise ValueError("All inputs must be 0 or 1")

return int(not all(inputs))
Comment thread
TTAAAN marked this conversation as resolved.


if __name__ == "__main__":
import doctest

Expand Down
Loading