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 to create a recursive function that removes odd digits of an integer

I just started working with recursive functions and I have to create a function that receives an integer and returns a new number that contains only the even number, for example if it receives 23456 it should return 246. This it what I’ve tried:

def newInt(n):
    dig = n % 10
    if dig % 2 == 1:
        return newInt(n//10)
    elif dig % 2 == 0:
        return str(n) + newInt(n//10)

print(newInt(32))

But I’m getting the following error code:

RecursionError: maximum recursion depth exceeded in __instancecheck__

Any hints on what should I do to fix it?

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

>Solution :

Your issue is that you have no condition to stop recursion – every call to newInt results in another call. One way to stop would be to check if n is less than 10 and then just return n if it is even. For example:

def newInt(n):
    if n < 10:
        return n if n % 2 == 0 else 0
    dig = n % 10
    if dig % 2 == 1:
        return newInt(n//10)
    elif dig % 2 == 0:
        return newInt(n//10) * 10 + dig

Note I have modified your function to return an integer rather than a string.

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