Skip to content

Added decimal_to_binary_recursion.py [Hacktoberfest] #3266

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 8 commits into from
Oct 14, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions conversions/decimal_to_binary_recursion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
def binary_recursive(decimal: int) -> str:
"""
This takes in a positive integer value
and returns its binary equivalent.
>>> binary_recursive(1000)
'1111101000'
>>> binary_recursive("72")
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for //: 'str' and 'int'
>>> binary_recursive("number")
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for //: 'str' and 'int'
"""
# Initialize exit base of the recursion function
if decimal == 1 or decimal == 0:
return str(decimal)
result = binary_recursive(decimal // 2) + str(decimal % 2)
return str(result)
Copy link
Member

Choose a reason for hiding this comment

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

I am not a fan of this change. Creating a variable that has a lifetime of just two lines is not helpful unless it shortens a very long line or the variable name documents something that is not obvious. result in this context does neither. binary_recursive() is documented as returning a str so it is OK to add a str to it.



def main(number: str) -> str:
"""
This function takes a parameter "number",
raises a ValueError for wrong inputs,
calls the function above and returns 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()
negative = False

if number.startswith("-"):
negative = True
number = number[1:]

if number.isnumeric():
if negative:
binary = "-0b" + binary_recursive(int(number))
else:
binary = "0b" + binary_recursive(int(number))
return binary
else:
raise ValueError("Input value is not an integer")


if __name__ == "__main__":
from doctest import testmod

testmod()