forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecimal_to_binary.py
109 lines (92 loc) · 3.25 KB
/
decimal_to_binary.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""Convert a Decimal Number to a Binary Number."""
defdecimal_to_binary_iterative(num: int) ->str:
"""
Convert an Integer Decimal Number to a Binary Number as str.
>>> decimal_to_binary_iterative(0)
'0b0'
>>> decimal_to_binary_iterative(2)
'0b10'
>>> decimal_to_binary_iterative(7)
'0b111'
>>> decimal_to_binary_iterative(35)
'0b100011'
>>> # negatives work too
>>> decimal_to_binary_iterative(-2)
'-0b10'
>>> # other floats will error
>>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> # strings will error as well
>>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'str' object cannot be interpreted as an integer
"""
ifisinstance(num, float):
raiseTypeError("'float' object cannot be interpreted as an integer")
ifisinstance(num, str):
raiseTypeError("'str' object cannot be interpreted as an integer")
ifnum==0:
return"0b0"
negative=False
ifnum<0:
negative=True
num=-num
binary: list[int] = []
whilenum>0:
binary.insert(0, num%2)
num>>=1
ifnegative:
return"-0b"+"".join(str(e) foreinbinary)
return"0b"+"".join(str(e) foreinbinary)
defdecimal_to_binary_recursive_helper(decimal: int) ->str:
"""
Take a positive integer value and return its binary equivalent.
>>> decimal_to_binary_recursive_helper(1000)
'1111101000'
>>> decimal_to_binary_recursive_helper("72")
'1001000'
>>> decimal_to_binary_recursive_helper("number")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'number'
"""
decimal=int(decimal)
ifdecimalin (0, 1): # Exit cases for the recursion
returnstr(decimal)
div, mod=divmod(decimal, 2)
returndecimal_to_binary_recursive_helper(div) +str(mod)
defdecimal_to_binary_recursive(number: str) ->str:
"""
Take an integer value and raise ValueError for wrong inputs,
call the function above and return the output with prefix "0b" & "-0b"
for positive and negative integers respectively.
>>> decimal_to_binary_recursive(0)
'0b0'
>>> decimal_to_binary_recursive(40)
'0b101000'
>>> decimal_to_binary_recursive(-40)
'-0b101000'
>>> decimal_to_binary_recursive(40.8)
Traceback (most recent call last):
...
ValueError: Input value is not an integer
>>> decimal_to_binary_recursive("forty")
Traceback (most recent call last):
...
ValueError: Input value is not an integer
"""
number=str(number).strip()
ifnotnumber:
raiseValueError("No input value was provided")
negative="-"ifnumber.startswith("-") else""
number=number.lstrip("-")
ifnotnumber.isnumeric():
raiseValueError("Input value is not an integer")
returnf"{negative}0b{decimal_to_binary_recursive_helper(int(number))}"
if__name__=="__main__":
importdoctest
doctest.testmod()
print(decimal_to_binary_recursive(input("Input a decimal number: ")))