TheAlgorithms-Python
52 строки · 1.4 Кб
1# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
2
3
4def binary_and(a: int, b: int) -> str:
5"""
6Take in 2 integers, convert them to binary,
7return a binary number that is the
8result of a binary and operation on the integers provided.
9
10>>> binary_and(25, 32)
11'0b000000'
12>>> binary_and(37, 50)
13'0b100000'
14>>> binary_and(21, 30)
15'0b10100'
16>>> binary_and(58, 73)
17'0b0001000'
18>>> binary_and(0, 255)
19'0b00000000'
20>>> binary_and(256, 256)
21'0b100000000'
22>>> binary_and(0, -1)
23Traceback (most recent call last):
24...
25ValueError: the value of both inputs must be positive
26>>> binary_and(0, 1.1)
27Traceback (most recent call last):
28...
29TypeError: 'float' object cannot be interpreted as an integer
30>>> binary_and("0", "1")
31Traceback (most recent call last):
32...
33TypeError: '<' not supported between instances of 'str' and 'int'
34"""
35if a < 0 or b < 0:
36raise ValueError("the value of both inputs must be positive")
37
38a_binary = str(bin(a))[2:] # remove the leading "0b"
39b_binary = str(bin(b))[2:] # remove the leading "0b"
40
41max_len = max(len(a_binary), len(b_binary))
42
43return "0b" + "".join(
44str(int(char_a == "1" and char_b == "1"))
45for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
46)
47
48
49if __name__ == "__main__":
50import doctest
51
52doctest.testmod()
53