Skip to content

bin(num). convert ZERO and negative decimal numbers to binary. #1093

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 3, 2019
19 changes: 9 additions & 10 deletions conversions/decimal_to_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,23 @@


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)
'0'
'0b0'
>>> decimal_to_binary(2)
'10'
'0b10'
>>> decimal_to_binary(7)
'111'
'0b111'
>>> decimal_to_binary(35)
'100011'
'0b100011'
>>> # negatives work too
>>> decimal_to_binary(-2)
'-10'
'-0b10'
>>> # floats are acceptable if equivalent to an int
>>> decimal_to_binary(2)
'10'
>>> decimal_to_binary(2.0)
'0b10'
>>> # other floats will error
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
Expand All @@ -35,9 +34,9 @@ def decimal_to_binary(num):
True
"""
assert type(num) in (int, float) and num == int(num)

num = int(num)
Copy link
Member

@cclauss cclauss Aug 2, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The following test fails...

>>> decimal_to_binary(2.0) == bin(2.0)
True

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cclauss bin(2.0) raises exception. And my code also raises exception. But the test still fails. Any idea how to resolve this issue? Can I just hard code the error in the doctests?
`**********************************************************************
File "decimal_to_binary.py", line 34, in main.decimal_to_binary
Failed example:
decimal_to_binary(2.0) == bin(2.0) # doctest: +ELLIPSIS
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python3.6/doctest.py", line 1330, in __run
compileflags, 1), test.globs)
File "<doctest main.decimal_to_binary[9]>", line 1, in
decimal_to_binary(2.0) == bin(2.0) # doctest: +ELLIPSIS
File "decimal_to_binary.py", line 38, in decimal_to_binary
raise TypeError("'float' object cannot be interpreted as an integer")
TypeError: 'float' object cannot be interpreted as an integer


`

if num == 0:
return 0
return "0b0"

negative = False

Expand Down