forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_to_decimal.py
More file actions
Latest commit
43 lines (39 loc) · 1.25 KB
/
Copy pathbinary_to_decimal.py
File metadata and controls
43 lines (39 loc) · 1.25 KB
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
defbin_to_decimal(bin_string: str) ->int:
"""
Convert a binary value to its decimal equivalent
>>> bin_to_decimal("101")
5
>>> bin_to_decimal(" 1010 ")
10
>>> bin_to_decimal("-11101")
-29
>>> bin_to_decimal("0")
0
>>> bin_to_decimal("a")
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
>>> bin_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> bin_to_decimal("39")
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
"""
bin_string=str(bin_string).strip()
ifnotbin_string:
raiseValueError("Empty string was passed to the function")
is_negative=bin_string[0] =="-"
ifis_negative:
bin_string=bin_string[1:]
ifnotall(charin"01"forcharinbin_string):
raiseValueError("Non-binary value was passed to the function")
decimal_number=0
forcharinbin_string:
decimal_number=2*decimal_number+int(char)
return-decimal_numberifis_negativeelsedecimal_number
if__name__=="__main__":
fromdoctestimporttestmod
testmod()