Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I skip a piece of code in recursion?

def bin_to_decimal(inp, degree=0, result=0):
arr = []
for i in inp:
    arr.append(i)
if not arr:
    return result
else:
    x = arr.pop(-1)
    result += int(x)**degree
    return bin_to_decimal(inp, degree+1, result)


bin_to_decimal('1001')

Is it possible to skip this part of function, when I call recursion?

arr = []
for i in inp:
    arr.append(i)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use:

def bin_to_decimal(inp, degree=0, result=0, skip=False):
    if skip:
        arr = []
        for i in inp:
            arr.append(i)
    if not arr:
        return result
    else:
        x = arr.pop(-1)
        result += int(x)**degree
        # Flag True to skip
        return bin_to_decimal(inp, degree+1, result, True)

But you will now have an unreferenced variable arr

  • along with a few more errors

I suggest you have a look at some other methods that you can use:

Built-in:

>>> int('1001',2)
9

Iteration:

def bin_to_decimal(inp):
    x = 0
    for i in inp:
        x = x*2 + int(i)
    return x
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading