Skip to content

Commit 4051f26

Browse files
authored
Nice!!
1 parent 42b5a9e commit 4051f26

File tree

1 file changed

+37
-34
lines changed

1 file changed

+37
-34
lines changed
Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,48 @@
1-
"""
2-
https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
3-
This function takes in 2 integer, convert them to binary and returns a binary
4-
in str format that is the result of an Binary OR operation from the 2 integer
5-
input.
1+
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
62

7-
Returns a binary resulted from 2 integer input in str format
8-
>>> binary_or(25,32)
9-
'0b111001'
103

11-
>>> binary_or(37,50)
12-
'0b110111'
13-
14-
>>> binary_or(21,30)
15-
'0b11111'
16-
17-
>>> binary_or(58,73)
18-
'0b1111011'
19-
"""
20-
21-
22-
def binary_or(a : int, b : int):
23-
if isinstance(a, float) or isinstance(b, float):
24-
raise TypeError("'Float' object cannot be implemented as an integer")
25-
if isinstance(a, str) or isinstance(b, str):
26-
raise TypeError("'str' object cannot be implemented as an integer")
27-
if a < 0 or b < 0:
28-
raise ValueError("the value of both input must be positive")
4+
def binary_or(a: int, b: int):
295
"""
30-
a_binary and b_binary are the binary of a and b in str format
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'
3133
"""
32-
a_binary = str(bin(a))[2:]
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"
3337
b_binary = str(bin(b))[2:]
34-
binary = []
3538
max_len = max(len(a_binary), len(b_binary))
36-
a_binary = a_binary.zfill(max_len)
37-
b_binary = b_binary.zfill(max_len)
38-
for char_a, char_b in zip(a_binary, b_binary):
39-
binary.append(str(int(char_a == "1" or char_b == "1")))
40-
return "0b" + "".join(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+
)
4143

4244

4345
if __name__ == "__main__":
4446
import doctest
47+
4548
doctest.testmod()

0 commit comments

Comments
 (0)