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

  1. 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!

  2. 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!