From 07112f893cc645fc5c5484f47c01f13727fc43dd Mon Sep 17 00:00:00 2001 From: Omkar Dattatraya Babar <116364228+omkar2508@users.noreply.github.com> Date: Sat, 26 Oct 2024 22:47:50 +0530 Subject: [PATCH] Adding algorithm Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. --- binary_and_operator.py | 47 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 binary_and_operator.py diff --git a/binary_and_operator.py b/binary_and_operator.py new file mode 100644 index 0000000..28ac32a --- /dev/null +++ b/binary_and_operator.py @@ -0,0 +1,47 @@ +def binary_and(a: int, b: int) -> str: + """ + Take in 2 integers, convert them to binary, + return a binary number that is the + result of a binary and operation on the integers provided. + + >>> binary_and(25, 32) + '0b000000' + >>> binary_and(37, 50) + '0b100000' + >>> binary_and(21, 30) + '0b10100' + >>> binary_and(58, 73) + '0b0001000' + >>> binary_and(0, 255) + '0b00000000' + >>> binary_and(256, 256) + '0b100000000' + >>> binary_and(0, -1) + Traceback (most recent call last): + ... + ValueError: the value of both inputs must be positive + >>> binary_and(0, 1.1) + Traceback (most recent call last): + ... + ValueError: Unknown format code 'b' for object of type 'float' + >>> binary_and("0", "1") + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' + """ + if a < 0 or b < 0: + raise ValueError("the value of both inputs must be positive") + + a_binary = format(a, "b") + b_binary = format(b, "b") + + max_len = max(len(a_binary), len(b_binary)) + + return "0b" + "".join( + str(int(char_a == "1" and char_b == "1")) + for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) + ) + + +if __name__ == "__main__": + binary_and(25, 32)