【问题标题】:Finding a common char between two strings recursively递归查找两个字符串之间的公共字符
【发布时间】:2014-04-17 22:24:09
【问题描述】:

我正在尝试编写一个递归代码,它接收 2 个字符串并返回 True 是它们有一个共同的字符,如果没有,则返回 False。 我首先编写了一个迭代代码,因为我认为它可能会有所帮助。 我遇到的问题是我不知道如何比较每个字符串中的所有字符。这是我到目前为止所做的: 迭代代码:

def any_char_present_it(s1,s2):
    if len(s1)==0 or len(s2)==0:
        return False
    for i in s2:
        for m in s1:
            if i==m:
                return True
    return False

递归代码:

def any_char_present(s1,s2):
    if len_rec(s2)==0:
        return False
    if s1[0]==s2[0]:
        return True
    return any_char_present(s1,s2[1:])

【问题讨论】:

  • 如果这是为了家庭作业,或者是第一次专门学习编程,我不会给出我个人用于解决这个问题的确切代码。不过,我会给你一个提示:你可以只使用集合并检查交叉点。 编辑: 糟糕,我看到有人在我写这篇文章时已经提供了一个基于集合的答案。哦,好吧。
  • 请记住,Python 语言在创建递归调用堆栈方面有很多开销,因此您会注意到您的迭代版本在输入较大时明显更快。如果在递归之前使用集合减少字符串肯定会更快,特别是如果您将自己限制为 ASCII 字符集。

标签: python python-3.x recursion


【解决方案1】:

您可以使用集合和集合论来检查常见字符,而无需自己遍历所有内容。

has_common_chars 将两个字符串转换为集合并找到它们的交集。如果交集的长度大于零,则至少有一个共同的字符。

s1 = "No one writes to the Colonel"
s2 = "Now is the time or all good men to come to the ade of the lemon."
s3 = "ZZZZ"

def has_common_chars(s1, s2):
    return len(set(s1) & set(s2)) > 0

print has_common_chars(s1, s2)
print has_common_chars(s2, s3)

>>> True
>>> False

编辑 s/联合/交叉点

【讨论】:

  • & 是交集,|是联合
  • 我真的应该在提交之前再读一遍这些东西。谢谢。
  • 除非这不是递归的。
【解决方案2】:

为了摆脱你的代码,你必须尝试每一种组合。为此,您可以在 return 语句中减少每个字符串,如下所示:

#return check(s1, decremented s2) or check(decremented s1, s2)
return (any_char_present(s1,s2[1:]) or any_char_present(s1[1:],s2))

这应该用尽所有可能的组合,以在两个字符串输入的任意点找到字符匹配。

完整代码:

def any_char_present(s1,s2):
    #update this if statement to check both strings
    #you can check for empty strings this way too
    if not s1 or not s2:
        return False
    if s1[0]==s2[0]:
        return True
    return (any_char_present(s1,s2[1:]) or any_char_present(s1[1:],s2))

print(any_char_present("xyz", "aycd"))

【讨论】:

  • bool(string) 如果 string == '' 则返回 False,否则返回 True,因此您可以检查 if not s1 or not s2: 或更简单的 if not (s1 and s2): 而不是使用 len你的第一个条件
猜你喜欢
  • 2013-09-13
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
相关资源
最近更新 更多