Skip to content

Commit d872eb8

Browse files
committed
refactor: enhance input validation in n_input_nand_gate function to check for empty list and values that are not 0 and 1
1 parent 2c6c4b2 commit d872eb8

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

boolean_algebra/nand_gate.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ def nand_gate(input_1: int, input_2: int) -> int:
3232

3333
def n_input_nand_gate(inputs: list[int]) -> int:
3434
"""
35-
Calculate NAND of a list of input values
35+
Generalization of nand_gate() to support n inputs.
36+
Calculate NAND of a list of input values.
37+
Returns 0 only when all inputs are 1, 1 otherwise.
38+
3639
>>> n_input_nand_gate([1, 0, 1, 1, 0])
3740
1
3841
>>> n_input_nand_gate([1, 1, 1, 1, 1])
@@ -45,14 +48,28 @@ def n_input_nand_gate(inputs: list[int]) -> int:
4548
>>> n_input_nand_gate([1, 1])
4649
0
4750
51+
>>> n_input_nand_gate([])
52+
Traceback (most recent call last):
53+
...
54+
ValueError: Input list cannot be empty
55+
4856
>>> n_input_nand_gate([1])
4957
Traceback (most recent call last):
5058
...
5159
ValueError: Input list must contain at least two elements
60+
61+
>>> n_input_nand_gate([2, 1])
62+
Traceback (most recent call last):
63+
...
64+
ValueError: All inputs must be 0 or 1
5265
"""
5366

67+
if len(inputs) == 0:
68+
raise ValueError("Input list cannot be empty")
5469
if len(inputs) < 2:
5570
raise ValueError("Input list must contain at least two elements")
71+
if not all(i in (0, 1) for i in inputs):
72+
raise ValueError("All inputs must be 0 or 1")
5673

5774
return int(not all(inputs))
5875

0 commit comments

Comments
 (0)