Home > Net >  Creating a recursive function that removes odd digits of an integer
Creating a recursive function that removes odd digits of an integer

Time:05-26

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 digits. For example if it receives 23456, it should return 246. This is 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:

RecursionError: maximum recursion depth exceeded in __instancecheck__

Any hints on what should I do to fix it?

CodePudding user response:

You need a base case. There's also no need to convert any of the integers to strings. Here is a working version of newInt() that resolves both of these issues:

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

CodePudding user response:

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.

CodePudding user response:

Here is a variant with divmod. Uncomment the print to see how it works:

def newInt(n):
    d,r = divmod(n,10)
    # print(n,d,r)
    if d == 0:
        return 0 if r%2 else r
    if r % 2:
        return newInt(d)
    else:
        return 10*newInt(d) r
    
print(newInt(212033450))

Output: 22040

CodePudding user response:

You don't even need to break out dig for each loop:

def newInt(n):
    if n:
        if n & 1:
            return newInt(n // 10)
        else:
            return 10 * newInt(n // 10)   (n % 10)
    return 0

CodePudding user response:

This is a rewrite of @mozway's algortihm using Python 3.10 match..case syntax -

def newInt(n):
  match divmod(n, 10):
    case (0, r) if r & 1:
      return 0
    case (0, r):
      return r
    case (d, r) if r & 1:
      return newInt(d)
    case (d, r):
      return 10 * newInt(d)   r
print(newInt(67120593306737201))
6200620

Note r & 1 is more efficient for testing if a number is even or odd. r % 2 performs division whereas & simply checks the first bit.

  • Related