How to create a recursive function that removes odd digits of an integer

Advertisements

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?

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

Leave a ReplyCancel reply