MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decimal_to_binary_recursive

Function decimal_to_binary_recursive

conversions/decimal_to_binary.py:74–101  ·  view source on GitHub ↗

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'

(number: str)

Source from the content-addressed store, hash-verified

72
73
74def decimal_to_binary_recursive(number: str) -> str:
75 """
76 Take an integer value and raise ValueError for wrong inputs,
77 call the function above and return the output with prefix "0b" & "-0b"
78 for positive and negative integers respectively.
79 >>> decimal_to_binary_recursive(0)
80 '0b0'
81 >>> decimal_to_binary_recursive(40)
82 '0b101000'
83 >>> decimal_to_binary_recursive(-40)
84 '-0b101000'
85 >>> decimal_to_binary_recursive(40.8)
86 Traceback (most recent call last):
87 ...
88 ValueError: Input value is not an integer
89 >>> decimal_to_binary_recursive("forty")
90 Traceback (most recent call last):
91 ...
92 ValueError: Input value is not an integer
93 """
94 number = str(number).strip()
95 if not number:
96 raise ValueError("No input value was provided")
97 negative = "-" if number.startswith("-") else ""
98 number = number.lstrip("-")
99 if not number.isnumeric():
100 raise ValueError("Input value is not an integer")
101 return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}"
102
103
104if __name__ == "__main__":

Callers 1

Calls 1

Tested by

no test coverage detected