forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_to_octal.py
45 lines (37 loc) · 1.17 KB
/
binary_to_octal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
The function below will convert any binary string to the octal equivalent.
>>> bin_to_octal("1111")
'17'
>>> bin_to_octal("101010101010011")
'52523'
>>> bin_to_octal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> bin_to_octal("a-1")
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
"""
defbin_to_octal(bin_string: str) ->str:
ifnotall(charin"01"forcharinbin_string):
raiseValueError("Non-binary value was passed to the function")
ifnotbin_string:
raiseValueError("Empty string was passed to the function")
oct_string=""
whilelen(bin_string) %3!=0:
bin_string="0"+bin_string
bin_string_in_3_list= [
bin_string[index : index+3]
forindexinrange(len(bin_string))
ifindex%3==0
]
forbin_groupinbin_string_in_3_list:
oct_val=0
forindex, valinenumerate(bin_group):
oct_val+=int(2** (2-index) *int(val))
oct_string+=str(oct_val)
returnoct_string
if__name__=="__main__":
fromdoctestimporttestmod
testmod()