Home > Blockchain >  python how many moves to get to zero
python how many moves to get to zero

Time:11-06

I have tried to do this task in a lot of ways but none of it works.

The user enters a natural number n. In one move, its largest digit is subtracted from the number. In the next move, its highest digit is subtracted from the result, etc. The program needs to determine and print how many moves it takes to get to zero. For example, number 24 requires five moves (24 → 20 → 18 → 10 → 9 → 0).

Here is what I've done so far. I know how to find the largest digit but how can I put this into a loop to substract largest digit from result ?

num = int(input("Enter natural number "))

if num <= 0:
    print("That is not a natural number")
else:
    max = 0
    while num > 0:
        digit = num % 10
        if max < digit:
            max = digit
        num = num // 10
    print("Largest Digit is : ", max)

CodePudding user response:

You could try with a string and max:

num = int(input("Enter natural number "))

if num <= 0:
    print("That is not a natural number")
else:
    ntimes = 0
    while num > 0:
        num -= int(max(str(num)))
        ntimes  = 1
    print(ntimes)

Output:

5

CodePudding user response:

In case you have the requirement of not casting the number into a string to obtain its digits you can use divmod:

def get_natural_num_input(prompt: str) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt))
            if num <= 0:
                print("Error: Not a natural number, try again...")
            else:
                break
        except ValueError:
            print("Error: Enter a integer, try again...")
    return num

def get_digits(num: int) -> list[int]:
    digits = []
    while num > 0:
        num, digit = divmod(num, 10)
        digits.append(digit)
    return digits

def moves_to_get_zero(num: int) -> int:
    moves = 0
    while num != 0:
        num -= max(get_digits(num))
        moves  = 1
    return moves

num = get_natural_num_input("Enter a natural number: ")
print(f'moves_to_get_zero({num}) = {moves_to_get_zero(num)}')

Example Usage:

Enter a natural number: 24
moves_to_get_zero(24) = 5
  • Related