给定一串数字,返回最大可能的双调数作为整数

问题描述 投票:0回答:1

给定一个函数largest_bitonic_at_most(n),找到最大的正双调整数并返回它。

这个问题中什么被认为是双调的?

  1. 如果仅按升序排列,则为双调(例如 123456、15687)
  2. 如果仅按降序排列,则为双调(例如 964441、7521)
  3. 如果先增加,然后减少,则为双调(例如 12368862, 2952)
  4. 只要符合前 3 个条件,重复的数字仍然有效(例如 77777、12222521)

如果数字不是双调的,则必须找到仍然是双调的最大正整数 调用示例 1: 最大位元数 (227942) 返回1: 227942 调用示例 2: 最大位元数 (28052) 返回2: 28000 调用示例 3: 最大位元数(268472) 返回3: 268444

条件:

  • 目前只能使用基本的Python命令(例如if else、递归、赋值)
  • 您可以查看我尝试制作的代码作为参考。

我已经被困了整整8个小时,我实在受不了了。这是我到目前为止的代码。我真的需要一些帮助

def largest_bitonic_at_most(n):
    def helper(n):
        n = str(n)
        length = len(n)
        if length > 2:
            if n[0] <= n[1]:
                return n[0] + helper(n[1:])
            elif n[0] > n[1]:
                if n[1] >= n[2]:
                    return n[0] + helper(n[1:])
                else:
                    return n[0] + (n[1] * (length - 1))
            else:
                return n[0]
        elif length <= 2 and length > 0:
            if n[0] >= n[1]:
                return n[0] * 2
            else:
                return n

    x = helper(n)
    return int(x)

以下是一些示例模拟和结果。

print(largest_bitonic_at_most(11118) #11118
print(largest_bitonic_at_most(211144) #211144 should be 211111
print(largest_bitonic_at_most(1204) #1200
print(largest_bitonic_at_most(789123) #789111
python recursion
1个回答
0
投票

您的代码只能在

return n[0] + (n[1] * (length - 1))
时达到
n[0] > n[1]
的情况,但这也应该在
n[0] == n[1]
和前面的字符对出现下降趋势时发生。但你的函数无法检测到这一点,因为它只查看
n[0]
n[1]
n[2]
之间的关系,而不知道之前发生了什么。

我建议你用布尔值记住你是否已经在“下降”,因为当达到该状态时,任何向上方向的运动(无论是立即发生还是稍后发生)都应该导致上述情况,其中相同的数字重复直到结束。

这是一种可能的方法:

def largest_bitonic_at_most(n):
    going_down = False
    limit = "0"
    res = []

    for c in str(n):
        if going_down:
            if c > limit:
                c = limit
        elif c < limit:
            going_down = True
        res.append(c)
        limit = c

    return int("".join(res))
© www.soinside.com 2019 - 2024. All rights reserved.