forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecimal_to_binary_recursion.py
More file actions
Latest commit
53 lines (48 loc) · 1.51 KB
/
Copy pathdecimal_to_binary_recursion.py
File metadata and controls
53 lines (48 loc) · 1.51 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
44
45
46
47
48
49
50
51
52
53
defbinary_recursive(decimal: int) ->str:
"""
Take a positive integer value and return its binary equivalent.
>>> binary_recursive(1000)
'1111101000'
>>> binary_recursive("72")
'1001000'
>>> binary_recursive("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)
returnbinary_recursive(div) +str(mod)
defmain(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.
>>> main(0)
'0b0'
>>> main(40)
'0b101000'
>>> main(-40)
'-0b101000'
>>> main(40.8)
Traceback (most recent call last):
...
ValueError: Input value is not an integer
>>> main("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{binary_recursive(int(number))}"
if__name__=="__main__":
fromdoctestimporttestmod
testmod()