[英]Using recursion to find subsequences
I need a program to return True
if one string ( s2
) can be turned into another string ( s1
) only by removing characters from s2
. 如果仅通过从
s2
删除字符就可以将一个字符串( s2
)转换为另一字符串( s1
),则需要一个程序返回True
。 So for example if s1 = star
and s2 = swewtffsafefr
it would return True
因此,例如,如果
s1 = star
和s2 = swewtffsafefr
,它将返回True
I've come up with this so far: 到目前为止,我已经提出了:
def subsequence(s1, s2, pos=0):
if pos < len(s1):
subsequence(s1,s2, pos+1)
else:
return 0
I can't figure out how to make it remove characters in s2
that aren't in s1
我无法弄清楚如何使它删除字符
s2
不在s1
so you know you want a recursive function subseq(s1,s2)
所以你知道你想要一个递归函数
subseq(s1,s2)
first you need to come up with your basecases 首先,您需要提出您的基本案例
next you need to put that into code 接下来,您需要将其放入代码中
if s1 in s2:return True
if not s1: return True
if not s2: return False
#everything else
for everything else we need to break it down further 对于其他一切,我们需要进一步分解
. 。
def subseq(s1,s2):
if s1 in s2: return True
if not s1: return True
if not s2: return False
#everything else
if s1[0] == s2[0]: return subseq(s1[1:],s2[1:])
return subseq(s1,s2[1:])
To remove chars in s2 that are not in s1 is not hard, there are a number of approaches 要删除不属于s1的s2中的字符并不难,有许多方法
set_s1 = set([item for item in s1])
set_s2 = set([item for item in s2])
This gets you the unique characters in s1 and s2 这使您获得s1和s2中的唯一字符
Now to identify the values in s2 not in s1 现在确定s2中的值而不是s1中的值
diff = set_s2.difference(set_s1)
Now to remove the characters from s2 in the diff (those in s2 not in s1) 现在从diff中的s2中删除字符(s2中的字符不在s1中)
if len(diff) == 0:
break
else:
new_s2 = ''
for c in s2:
if c not in diff:
new_s2 = new_s2 + c
Problem you still have is removing duplicates 您仍然遇到的问题是删除重复项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.