|
18 | 18 |
|
19 | 19 | def and_gate(input_1: int, input_2: int) -> int: |
20 | 20 | """ |
21 | | - Calculate AND of the input values |
| 21 | + Calculate AND of two binary input values. |
22 | 22 |
|
23 | 23 | >>> and_gate(0, 0) |
24 | 24 | 0 |
25 | 25 | >>> and_gate(0, 1) |
26 | 26 | 0 |
27 | | - >>> and_gate(1, 0) |
28 | | - 0 |
29 | 27 | >>> and_gate(1, 1) |
30 | 28 | 1 |
| 29 | + >>> and_gate(2, 1) |
| 30 | + Traceback (most recent call last): |
| 31 | + ... |
| 32 | + ValueError: Both inputs must be 0 or 1 |
| 33 | + >>> and_gate(0, "1") |
| 34 | + Traceback (most recent call last): |
| 35 | + ... |
| 36 | + TypeError: Both inputs must be integers |
31 | 37 | """ |
32 | | - return int(input_1 and input_2) |
| 38 | + # Type validation |
| 39 | + if not isinstance(input_1, int) or not isinstance(input_2, int): |
| 40 | + raise TypeError("Both inputs must be integers") |
| 41 | + |
| 42 | + # Value validation |
| 43 | + if input_1 not in (0, 1) or input_2 not in (0, 1): |
| 44 | + raise ValueError("Both inputs must be 0 or 1") |
| 45 | + |
| 46 | + return input_1 & input_2 |
33 | 47 |
|
34 | 48 |
|
35 | 49 | def n_input_and_gate(inputs: list[int]) -> int: |
36 | 50 | """ |
37 | | - Calculate AND of a list of input values |
| 51 | + Calculate AND of a list of binary input values. |
38 | 52 |
|
39 | | - >>> n_input_and_gate([1, 0, 1, 1, 0]) |
40 | | - 0 |
41 | 53 | >>> n_input_and_gate([1, 1, 1, 1, 1]) |
42 | 54 | 1 |
| 55 | + >>> n_input_and_gate([1, 0, 1, 1, 0]) |
| 56 | + 0 |
| 57 | + >>> n_input_and_gate([]) |
| 58 | + Traceback (most recent call last): |
| 59 | + ... |
| 60 | + ValueError: Input list cannot be empty |
| 61 | + >>> n_input_and_gate([1, 2, 1]) |
| 62 | + Traceback (most recent call last): |
| 63 | + ... |
| 64 | + ValueError: All inputs in the list must be 0 or 1 |
| 65 | + >>> n_input_and_gate([1, "1"]) |
| 66 | + Traceback (most recent call last): |
| 67 | + ... |
| 68 | + TypeError: All inputs in the list must be integers |
43 | 69 | """ |
| 70 | + # Type validation for the list itself |
| 71 | + if not isinstance(inputs, list): |
| 72 | + raise TypeError("Input must be a list") |
| 73 | + |
| 74 | + # Edge case validation for an empty list |
| 75 | + if not inputs: |
| 76 | + raise ValueError("Input list cannot be empty") |
| 77 | + |
| 78 | + # Type and value validation for items within the list |
| 79 | + for item in inputs: |
| 80 | + if not isinstance(item, int): |
| 81 | + raise TypeError("All inputs in the list must be integers") |
| 82 | + if item not in (0, 1): |
| 83 | + raise ValueError("All inputs in the list must be 0 or 1") |
| 84 | + |
44 | 85 | return int(all(inputs)) |
45 | 86 |
|
46 | 87 |
|
|
0 commit comments