File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments