简体   繁体   English

使用递归查找子序列

[英]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 = stars2 = 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 首先,您需要提出您的基本案例

  1. s1 == s2 , for this we will return true s1 == s2,为此我们将返回true
  2. s1 is empty , for this we will also return true s1为空,为此我们也将返回true
  3. s2 is empty but s1 is not, we will return false s2为空但s1不是,我们将返回false
  4. everything else 其他一切

next you need to put that into code 接下来,您需要将其放入代码中

  1. if s1 in s2:return True
  2. if not s1: return True
  3. if not s2: return False
  4. #everything else

for everything else we need to break it down further 对于其他一切,我们需要进一步分解

  1. if s1[0] == s2[0] advance both pointers 如果s1 [0] == s2 [0]提前两个指针
  2. otherwise only advance s2 否则只能提前s2

.

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.

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