From e3131419048010d9d67441387da4e73755364cf2 Mon Sep 17 00:00:00 2001 From: Syed Waleed Hyder Date: Sat, 3 Aug 2019 20:00:10 +0200 Subject: [PATCH] bin(num). convert ZERO and negative decimal numbers to binary. (#1093) * bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * doctests still failing. * Doctests added. --- conversions/decimal_to_binary.py | 63 ++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 15 deletions(-) diff --git a/conversions/decimal_to_binary.py b/conversions/decimal_to_binary.py index 43ceee61a..934cf0dfb 100644 --- a/conversions/decimal_to_binary.py +++ b/conversions/decimal_to_binary.py @@ -2,24 +2,57 @@ def decimal_to_binary(num): - """Convert a Decimal Number to a Binary Number.""" + + """ + Convert a Integer Decimal Number to a Binary Number as str. + >>> decimal_to_binary(0) + '0b0' + >>> decimal_to_binary(2) + '0b10' + >>> decimal_to_binary(7) + '0b111' + >>> decimal_to_binary(35) + '0b100011' + >>> # negatives work too + >>> decimal_to_binary(-2) + '-0b10' + >>> # other floats will error + >>> decimal_to_binary(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('0xfffff') # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'str' object cannot be interpreted as an integer + """ + + if type(num) == float: + raise TypeError("'float' object cannot be interpreted as an integer") + if type(num) == str: + raise TypeError("'str' object cannot be interpreted as an integer") + + if num == 0: + return "0b0" + + negative = False + + if num < 0: + negative = True + num = -num + binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 - return "".join(str(e) for e in binary) + + if negative: + return "-0b" + "".join(str(e) for e in binary) + + return "0b" + "".join(str(e) for e in binary) -def main(): - """Print binary equivelents of decimal numbers.""" - print("\n2 in binary is:") - print(decimal_to_binary(2)) # = 10 - print("\n7 in binary is:") - print(decimal_to_binary(7)) # = 111 - print("\n35 in binary is:") - print(decimal_to_binary(35)) # = 100011 - print("\n") - - -if __name__ == '__main__': - main() +if __name__ == "__main__": + import doctest + doctest.testmod()