Skip to content

Problem 3: Monotone (100pts)

Problem

A number is said to have monotone digits if its digits have an non-decreasing order from left to right when written down. For example, 1234 and 24555 have monotone digits, while 22000130 and 2025 don't.

Now, please write a recursive function is_monotone, which takes as input a number n and returns whether n has monotone digits. Specifically, is_monotone returns True if n has monotone digits, and returns False if not.

如果一个数的每一位从左到右书写时具有非递减的顺序,那么这个数被称为“具有单调数字”。例如,123424555 具有单调数字,而 220001302025 没有。

现在,请编写一个递归函数 is_monotone,它接受一个数 n 作为输入,并返回 n 是否具有单调数字。具体来说,如果 n 具有单调数字,is_monotone 返回 True,否则返回 False

def is_monotone(n):
    """Returns whether n has monotone digits.
    Implement using recursion!

    >>> is_monotone(22000130)
    False
    >>> is_monotone(1234)
    True
    >>> is_monotone(24555)
    True
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(LAB_SOURCE_FILE, 'is_monotone', ['While', 'For'])
    True
    """
    "*** YOUR CODE HERE ***"

Hints

  • 可以每次只判断最后两位,若符合条件则删除最后一位,开始递归。

Solutions

def is_monotone(n):

    # Base Case: A single-digit number (or n=0) is always monotone.
    if n < 10:
        return True

    # Recursive Step: Check the last two digits.
    # The last digit
    last = n % 10
    # The second-to-last digit
    second_last = (n // 10) % 10

    # Condition: For the digits to be non-decreasing (monotone), the second-to-last 
    # digit must be less than or equal to the last digit.
    if second_last > last:
        return False

    # If the last two digits are monotone, proceed to check the rest of the number (n // 10)
    # The result is True only if both the current check and the rest of the number are monotone.
    return is_monotone(n // 10)

压行

def is_monotone(n):
    return True if n < 10 else False if (n % 10) < (n % 100 // 10) else is_monotone(n // 10)