Skip to content

Commit af2c1c8

Browse files
Updated the error handling in and_gate.py (#13236)
* Updated the error handling in and_gate.py * Apply batched suggestions from code review Co-authored-by: Christian Clauss <cclauss@me.com> --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent cbe3204 commit af2c1c8

1 file changed

Lines changed: 48 additions & 3 deletions

File tree

boolean_algebra/and_gate.py

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
def and_gate(input_1: int, input_2: int) -> int:
2020
"""
21-
Calculate AND of the input values
21+
Calculate AND of two binary input values.
2222
2323
>>> and_gate(0, 0)
2424
0
@@ -28,19 +28,64 @@ def and_gate(input_1: int, input_2: int) -> int:
2828
0
2929
>>> and_gate(1, 1)
3030
1
31+
>>> and_gate(2, 1)
32+
Traceback (most recent call last):
33+
...
34+
ValueError: Both inputs must be 0 or 1
35+
>>> and_gate(0, "1")
36+
Traceback (most recent call last):
37+
...
38+
TypeError: Both inputs must be integers
3139
"""
32-
return int(input_1 and input_2)
40+
# Type validation
41+
if not isinstance(input_1, int) or not isinstance(input_2, int):
42+
raise TypeError("Both inputs must be integers")
43+
44+
# Value validation
45+
if input_1 not in (0, 1) or input_2 not in (0, 1):
46+
raise ValueError("Both inputs must be 0 or 1")
47+
48+
return input_1 & input_2
3349

3450

3551
def n_input_and_gate(inputs: list[int]) -> int:
3652
"""
37-
Calculate AND of a list of input values
53+
Calculate AND of a list of binary input values.
3854
3955
>>> n_input_and_gate([1, 0, 1, 1, 0])
4056
0
4157
>>> n_input_and_gate([1, 1, 1, 1, 1])
4258
1
59+
>>> n_input_and_gate([1, 0, 1, 1, 0])
60+
0
61+
>>> n_input_and_gate([])
62+
Traceback (most recent call last):
63+
...
64+
ValueError: Input list cannot be empty
65+
>>> n_input_and_gate([1, 2, 1])
66+
Traceback (most recent call last):
67+
...
68+
ValueError: All inputs in the list must be 0 or 1
69+
>>> n_input_and_gate([1, "1"])
70+
Traceback (most recent call last):
71+
...
72+
TypeError: All inputs in the list must be integers
4373
"""
74+
# Type validation for the list itself
75+
if not isinstance(inputs, list):
76+
raise TypeError("Input must be a list")
77+
78+
# Edge case validation for an empty list
79+
if not inputs:
80+
raise ValueError("Input list cannot be empty")
81+
82+
# Type and value validation for items within the list
83+
for item in inputs:
84+
if not isinstance(item, int):
85+
raise TypeError("All inputs in the list must be integers")
86+
if item not in (0, 1):
87+
raise ValueError("All inputs in the list must be 0 or 1")
88+
4489
return int(all(inputs))
4590

4691

0 commit comments

Comments
 (0)