Skip to content

Commit b22596c

Browse files
mohammadreza490cclaussrealDuYuanChao
authored
bin_to_octal (TheAlgorithms#2431)
* bin_to_octal Converts binary values to the octal equivalent. * Update bin_to_octal * Update conversions/bin_to_octal Co-authored-by: Christian Clauss <cclauss@me.com> * Update conversions/bin_to_octal Co-authored-by: Du Yuanchao <shellhub.me@gmail.com> * Update conversions/bin_to_octal Co-authored-by: Du Yuanchao <shellhub.me@gmail.com> * Update conversions/bin_to_octal Co-authored-by: Du Yuanchao <shellhub.me@gmail.com> * Rename bin_to_octal to bin_to_octal.py Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: Du Yuanchao <shellhub.me@gmail.com>
1 parent 697495b commit b22596c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

conversions/bin_to_octal.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
The function below will convert any binary string to the octal equivalent.
3+
4+
>>> bin_to_octal("1111")
5+
'17'
6+
7+
>>> bin_to_octal("101010101010011")
8+
'52523'
9+
10+
>>> bin_to_octal("")
11+
Traceback (most recent call last):
12+
...
13+
ValueError: Empty string was passed to the function
14+
>>> bin_to_octal("a-1")
15+
Traceback (most recent call last):
16+
...
17+
ValueError: Non-binary value was passed to the function
18+
"""
19+
20+
21+
def bin_to_octal(bin_string: str) -> str:
22+
if not all(char in "01" for char in bin_string):
23+
raise ValueError("Non-binary value was passed to the function")
24+
if not bin_string:
25+
raise ValueError("Empty string was passed to the function")
26+
oct_string = ""
27+
while len(bin_string) % 3 != 0:
28+
bin_string = "0" + bin_string
29+
bin_string_in_3_list = [
30+
bin_string[index: index + 3]
31+
for index, value in enumerate(bin_string)
32+
if index % 3 == 0
33+
]
34+
for bin_group in bin_string_in_3_list:
35+
oct_val = 0
36+
for index, val in enumerate(bin_group):
37+
oct_val += int(2 ** (2 - index) * int(val))
38+
oct_string += str(oct_val)
39+
return oct_string
40+
41+
42+
if __name__ == "__main__":
43+
from doctest import testmod
44+
45+
testmod()

0 commit comments

Comments
 (0)