递归寻找两个字符串的公共字符
我正在尝试写一个递归的代码,这个代码接收两个字符串,如果它们有共同的字符就返回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:])
2 个回答
1
根据你的代码,你需要尝试每一种组合。为了做到这一点,你可以在返回语句中减少每个字符串的值,像这样:
#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"))
2
你可以使用集合和集合理论来检查两个字符串中是否有相同的字符,而不需要自己一个个去比对。
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
编辑:把“并集”改成“交集”