educative.io

Could you please explain how your solution is optimal than mine

Hey,

I came up with following solution:

    def decimalToBinary(testVariable):
  
       if testVariable == 1: return '1'
  
    return decimalToBinary(testVariable//2) + str(testVariable%2)

Editor gives a “recursion depth exceeded” error. Up on checking edu’s solution, I found an extra recursive call with testVariable%2.

Intuitively, I feel edu’s solution takes more recursive calls to get to solution, hence occupying more space on recursive stack; but for some reason this solution is accepted.

Just curious on why a function with more recursive calls went through than my solution.


Course: https://www.educative.io/courses/recursion-in-python
Lesson: https://www.educative.io/courses/recursion-in-python/YMR2yRMkRGW

Hi @Amit_Adiraju_Narasim,

Thank you for sharing your approach to the problem and for your insightful analysis of the solutions provided. I appreciate your attention to detail and your commitment to understanding the intricacies of recursive algorithms.

Upon reviewing your solution, I noticed a minor oversight in handling all possible base cases. To ensure robustness and correctness, I’ve made some adjustments to your solution:

def decimalToBinary(testVariable):
    if testVariable == 0:
        return '0'
    elif testVariable == 1:
        return '1'
    else:
        return decimalToBinary(testVariable // 2) + str(testVariable % 2)

In this corrected version, I’ve included additional base cases to handle scenarios where the input testVariable is either 0 or 1. This ensures that the function covers all possible input values and provides the correct binary representation for each case.

I appreciate your dedication to improving your coding skills and your willingness to engage with the learning process. Keep up the great work, and don’t hesitate to reach out if you have any further questions or insights!