繁体   English   中英

递归查找两个字符串之间的公共字符

[英]Finding a common char between two strings recursively

我试图编写一个接收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:])

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

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 /工会/交叉点

只是为了关闭代码,您必须尝试各种组合。 为此,您可以这样在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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM