【问题标题】:Terminate the recursion before discovering all the states在发现所有状态之前终止递归
【发布时间】:2020-06-19 19:26:29
【问题描述】:

我编写了以下函数,程序的输出是正确的。但是,程序在进行递归时会发现所有可能的状态,这意味着程序可以更高效地完成。基本上,我需要在输出为True 时终止递归,而不是发现其他状态。任何想法表示赞赏!

checked_strings = []

# idx - current index of string a
# input string a
# output string b
def abbreviation(idx, a, b):
    if a in checked_strings:
        return False
    if idx == len(a):
        return a == b
    flag1 = flag2 = False
    if a[idx].islower():
        new_string1 = a[:idx] + a[idx+1:]
        flag1 = abbreviation(idx, new_string1, b)
        if not flag1:
            checked_strings.append(new_string1)
        new_string2 = a[:idx] + a[idx].upper() + a[idx+1:]
        flag2 = abbreviation(idx + 1, new_string2, b)
        if not flag2:
            checked_strings.append(new_string2)
    return flag1 or flag2 or abbreviation(idx + 1, a, b)

问题描述如下:

给定两个字符串abb 大写)。使用以下规则查找是否可以从字符串a 中获取字符串b

  1. 如果字符串的字符是小写的,那么你允许删除它。

  2. 如果字符串的字符是小写的,那么你可以把这个字符变成大写。

  3. 字符可以跳过。

输入如下:

1
daBcd
ABC

虽然输出应该是:

true 

【问题讨论】:

  • 也许您可以分享一些示例输入和预期输出? abbreviation 究竟做了什么?
  • 我现在要添加它们
  • 请提供预期的[最小的、可重现的示例](stackoverflow.com/help/minimal-reproducible-example)。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。另外,请从intro tour 重复[如何提问](stackoverflow.com/help/how-to-ask)。你没有解释你的算法,也没有追踪它当前的操作。由于您使用了无意义的变量名,我们无法轻易重构您的逻辑——我们根本不应该做这项工作。
  • 我认为问题在于,即使 flag1 成功,您也在调用 flag2 的缩写。如果 flag1 成功,您应该跳过第二个缩写调用,这样您就不会继续查找状态。 (这是一个猜测,因为正如 Prune 所说,目前还不清楚发生了什么。)
  • @KenShirriff 谢谢!现在可以了。

标签: python recursion termination


【解决方案1】:
checked_strings = []

# idx - current index of string a
# input string a
# output string b
def abbreviation(idx, a, b):
    if a in checked_strings:
        return False
    if idx == len(a):
        return a == b
    flag1 = flag2 = False
    if a[idx].islower():
        new_string1 = a[:idx] + a[idx+1:]
        flag1 = abbreviation(idx, new_string1, b)
        if flag1:
            return True
        else
            checked_strings.append(new_string1)
        new_string2 = a[:idx] + a[idx].upper() + a[idx+1:]
        flag2 = abbreviation(idx + 1, new_string2, b)
        if flag2:
            return True
        else
            checked_strings.append(new_string2)
    return abbreviation(idx + 1, a, b)

当其中一个标志为 True 时,您可以立即返回它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多