-4
\$\begingroup\$

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?

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

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))
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Please refrain from answering off-topic questions. There are plenty of on-topic questions that could use a review. \$\endgroup\$ – Mast May 18 at 17:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.