Skip to content

Commit 61dde44

Browse files
Firejay3cclauss
andauthored
Added binery_or_operator.py to bit manipulation file (#2331)
* added bitwise binary OR operator * Rename binary_OR_operator.py to binary_or_operator.py * Update binary_or_operator.py * Update binary_or_operator.py * Update bit_manipulation/binary_or_operator.py Co-authored-by: Christian Clauss <[email protected]> * Update binary_or_operator.py * Update binary_or_operator.py * Nice!! Co-authored-by: Christian Clauss <[email protected]>
1 parent 30126c2 commit 61dde44

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
2+
3+
4+
def binary_or(a: int, b: int):
5+
"""
6+
Take in 2 integers, convert them to binary, and return a binary number that is the
7+
result of a binary or operation on the integers provided.
8+
9+
>>> binary_or(25, 32)
10+
'0b111001'
11+
>>> binary_or(37, 50)
12+
'0b110111'
13+
>>> binary_or(21, 30)
14+
'0b11111'
15+
>>> binary_or(58, 73)
16+
'0b1111011'
17+
>>> binary_or(0, 255)
18+
'0b11111111'
19+
>>> binary_or(0, 256)
20+
'0b100000000'
21+
>>> binary_or(0, -1)
22+
Traceback (most recent call last):
23+
...
24+
ValueError: the value of both input must be positive
25+
>>> binary_or(0, 1.1)
26+
Traceback (most recent call last):
27+
...
28+
TypeError: 'float' object cannot be interpreted as an integer
29+
>>> binary_or("0", "1")
30+
Traceback (most recent call last):
31+
...
32+
TypeError: '<' not supported between instances of 'str' and 'int'
33+
"""
34+
if a < 0 or b < 0:
35+
raise ValueError("the value of both input must be positive")
36+
a_binary = str(bin(a))[2:] # remove the leading "0b"
37+
b_binary = str(bin(b))[2:]
38+
max_len = max(len(a_binary), len(b_binary))
39+
return "0b" + "".join(
40+
str(int("1" in (char_a, char_b)))
41+
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
42+
)
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)