# Finding The Largest Digit in a Number using a Recursive Function in Python [closed]

I tried it using the code given below.

big=0 ; c=0
def largest(n):
global c
c+=1
global big
if n//10!=0:
if big<n%10:
big=n%10
return largest(n//10)
if n//10==0:
if c==1:
return n
else:
return big


But, when I input more than one number in which the first number has the digit of all of them, then the output is the largest digit of the first number, which is repeated.

For example: If i input 3 numbers like

259, 33, 26


Then the output will be:

9
9
9


How to resolve this?

• Because big is a global which never resets – webdeb May 18 at 9:08
• Does it need to be recursive? Why not just cast to string split all and sort – webdeb May 18 at 9:11
• This is a homework from school, so I have to use recursion. If big never resets, how do I fix that? – Aritra Pal May 18 at 9:15
• As presented, the code does not work as intended: off-topic at CodeReview@SE. – greybeard May 18 at 9:22
• Get this working with reduce and then converting to an, honestly really poor use of recursion, is easy. – Peilonrayz May 18 at 9:42

As was pointed out, this question is off-topic here because this channel is for reviewing and improving code that works as designed. That said, an easy recursive solution using a normal outer function with a recursive inner function could look as follows:

def largestDigit(n):
def inner(d, n):
if n == 0:
return d
else:
return inner(max(d, n % 10), n // 10)
return inner(0, abs(n))


Edit: To keep with the topic of improving working code, here is a shorter version using an if expression instead of an if statement:

def largestDigit(n):
def inner(d, n):
return d if n == 0 else inner(max(d, n % 10), n // 10)
return inner(0, abs(n))

• Please refrain from answering off-topic questions. There are plenty of on-topic questions that could use a review. – Mast May 18 at 17:42