Home > database >  How to find minimum digit in a number using recursion [Python]
How to find minimum digit in a number using recursion [Python]

Time:11-13

I have a function that gets a number and should return the minimum digit. This is what I was trying to do, but maybe I didn't fully understand how recursion works.

def min_dig(num):
    minimum = 9
    if num < 10:
        return num
    min_dig(num / 10)
    if num % 10 < minimum:
        minimum = num % 10
    return minimum


print(min_dig(98918))

Output is 8 but supposed to be 1.

CodePudding user response:

I think what the recursion trying to do is like this:

def min_dig(num):
    if num < 10:
        return num
    return min(num % 10, min_dig(num // 10))

print(min_dig(98918))

If the number is smaller than 10, then its minimum digit is itself. If the number is larger than 10, we just compare its last digit and the minimum digit of the number composed of all its digits except the last digit, and return the smaller one.

CodePudding user response:

I have modified your function in a way that works and I think is simpler to understand.

def min_dig(number):
    if number < 10:
        return number
    else:
        return min(number % 10, min_dig(number // 10))

This also uses recursion, I just do it as the return. Here you basically compare (number % 10) and (min_dig(number // 10) and just return the lowest. This way you can compare all the digits in your number between them. Hope this helps.

CodePudding user response:

Lets start by thinking about this in the logic for now;

You get given a number, You split the number into an array of numbers, You loop through that array and store the first digit in a variable, For all of the next iterations of the array, you compare that index in the array with what's stored in the variable, and if it's smaller, you overwrite the variable with the new number, if not, continue, Return the number in the variable

Here's some Pseudocode that should help you out a little, you can convert it into python yourself

number = 98918
numberArray = number.split
smallest = numberArray[0]
for (digit in numberArray){
    if (digit < smallest){
        smallest = digit
    }
}
print(smallest)

CodePudding user response:

You have made minimum as your local variable so every time it will assign the value as 9. Try to make it global variable.

minimum = 9
def min_dig(num):
    global minimum
    if num < 10:
        return num
    min_dig(num // 10)
    if num % 10 < minimum:
        minimum = num % 10
    return minimum


print(min_dig(98918))
  • Related