Question
Write a function dec_to_bin(n) that takes a non-negative integer n and uses recursion to convert it from decimal to binary constructing and returning a string
-
Write a function dec_to_bin(n) that takes a non-negative integer n and uses recursion to convert it from decimal to binary constructing and returning a string version of the binary representation of that number. For example:
>>> dec_to_bin(5) result: '101' >>> dec_to_bin(12) result: '1100' >>> dec_to_bin(0) result: '0'
Notes/hints:
-
The function must use the recursive, right-to-left approach that we discussed in the lecture on binary numbers.
-
You will need two base cases.
-
Make sure that all return statements return a string and not an integer.
-
In lecture, we gave you an example of how the function should recursively process a number. You should use that example and other concrete cases to determine the appropriate logic for the recursive case.
-
In addition to the test cases provided above, make sure to try other test cases to ensure that your function works correctly in all cases!
-
-
Write a function bin_to_dec(b) that takes a string b that represents a binary number and uses recursion to convert the number from binary to decimal, returning the resulting integer. For example:
>>> bin_to_dec('101') result: 5 >>> bin_to_dec('1100') result: 12 >>> bin_to_dec('0') result: 0
Notes/hints:
-
The function must use the recursive, right-to-left approach that we discussed in the lecture on binary numbers.
-
You will again need two base cases. You may assume that the string passed in for b will never be empty.
-
Make sure that all return statements return an integer and not a string.
-
In lecture, we gave you an example of how the function should recursively process a string. You should use that example and other concrete cases to determine the appropriate logic for your recursive case.
-
In addition to the test cases provided above, make sure to try other test cases to ensure that your function works correctly in all cases!
-
I AM CONFUSED ABOUT HOW TO DO THIS WITH TWO BASE CASES.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started