-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
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
Changes from 1 commit
3f7750c
c4fc5c8
9d05f7f
31b2318
cba9e64
c995c41
997ba91
0812320
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,23 @@ | ||
""" Convert decimal values to binary using recursion method """ | ||
|
||
|
||
def bin_recursive(decimal: int) -> str: | ||
def binary_recursive(decimal: int) -> str: | ||
""" | ||
The funtion takes in a positive integer value | ||
This takes in a positive integer value | ||
and returns its binary equivalent. | ||
>>> bin_recursive(1000) | ||
>>> binary_recursive(1000) | ||
'1111101000' | ||
>>> bin_recursive("72") | ||
>>> binary_recursive("72") | ||
Traceback (most recent call last): | ||
... | ||
TypeError: unsupported operand type(s) for //: 'str' and 'int' | ||
>>> bin_recursive("number") | ||
>>> 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) | ||
return bin_recursive(decimal // 2) + str(decimal % 2) | ||
result = binary_recursive(decimal // 2) + str(decimal % 2) | ||
return str(result) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
|
||
|
||
def main(number: str) -> str: | ||
|
@@ -53,9 +51,9 @@ def main(number: str) -> str: | |
|
||
if number.isnumeric(): | ||
if negative: | ||
binary = "-0b" + bin_recursive(int(number)) | ||
binary = "-0b" + binary_recursive(int(number)) | ||
else: | ||
binary = "0b" + bin_recursive(int(number)) | ||
binary = "0b" + binary_recursive(int(number)) | ||
return binary | ||
else: | ||
raise ValueError("Input value is not an integer") | ||
|
Uh oh!
There was an error while loading. Please reload this page.