|
| 1 | +def binary_recursive(decimal: int) -> str: |
| 2 | + """ |
| 3 | + Take a positive integer value and return its binary equivalent. |
| 4 | + >>> binary_recursive(1000) |
| 5 | + '1111101000' |
| 6 | + >>> binary_recursive("72") |
| 7 | + '1001000' |
| 8 | + >>> binary_recursive("number") |
| 9 | + Traceback (most recent call last): |
| 10 | + ... |
| 11 | + ValueError: invalid literal for int() with base 10: 'number' |
| 12 | + """ |
| 13 | + decimal = int(decimal) |
| 14 | + if decimal in (0, 1): # Exit cases for the recursion |
| 15 | + return str(decimal) |
| 16 | + div, mod = divmod(decimal, 2) |
| 17 | + return binary_recursive(div) + str(mod) |
| 18 | + |
| 19 | + |
| 20 | +def main(number: str) -> str: |
| 21 | + """ |
| 22 | + Take an integer value and raise ValueError for wrong inputs, |
| 23 | + call the function above and return the output with prefix "0b" & "-0b" |
| 24 | + for positive and negative integers respectively. |
| 25 | + >>> main(0) |
| 26 | + '0b0' |
| 27 | + >>> main(40) |
| 28 | + '0b101000' |
| 29 | + >>> main(-40) |
| 30 | + '-0b101000' |
| 31 | + >>> main(40.8) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ValueError: Input value is not an integer |
| 35 | + >>> main("forty") |
| 36 | + Traceback (most recent call last): |
| 37 | + ... |
| 38 | + ValueError: Input value is not an integer |
| 39 | + """ |
| 40 | + number = str(number).strip() |
| 41 | + if not number: |
| 42 | + raise ValueError("No input value was provided") |
| 43 | + negative = "-" if number.startswith("-") else "" |
| 44 | + number = number.lstrip("-") |
| 45 | + if not number.isnumeric(): |
| 46 | + raise ValueError("Input value is not an integer") |
| 47 | + return f"{negative}0b{binary_recursive(int(number))}" |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + from doctest import testmod |
| 52 | + |
| 53 | + testmod() |
0 commit comments