diff --git a/boolean_algebra/or_gate.py b/boolean_algebra/or_gate.py index 0fd4e5a5dc18..2915b1da2363 100644 --- a/boolean_algebra/or_gate.py +++ b/boolean_algebra/or_gate.py @@ -29,6 +29,47 @@ def or_gate(input_1: int, input_2: int) -> int: return int((input_1, input_2).count(1) != 0) +def n_input_or_gate(inputs: list[int]) -> int: + """ + Generalization of or_gate() to support n inputs. + Calculate OR of a list of input values. + Returns 1 if any input is 1, 0 otherwise. + + >>> n_input_or_gate([0, 0, 0, 0, 0]) + 0 + >>> n_input_or_gate([0, 1, 0, 0, 0]) + 1 + >>> n_input_or_gate([1, 1, 1, 1, 1]) + 1 + + >>> n_input_or_gate([0, 1]) + 1 + + >>> n_input_or_gate([]) + Traceback (most recent call last): + ... + ValueError: Input list cannot be empty + + >>> n_input_or_gate([1]) + Traceback (most recent call last): + ... + ValueError: Input list must contain at least two elements + + >>> n_input_or_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: + 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(any(inputs)) + + if __name__ == "__main__": import doctest