简体   繁体   English

字符串递归问题

[英]string recursion problems

I am relatively new to python and especially recursion. 我是python的新手,尤其是递归。 I have been trying to solve this problem for a while now but it's bested me so far 我已经尝试解决这个问题已有一段时间了,但是到目前为止,它已经超越了我

I have to create a function that takes in 2 strings and uses recursion to see if elements from the first string are in the second string if so it returns true if not than it returns false say "Carpool" and "prlo" or "elephant" and "xph" in the first case the recursive argument would return True and in the second case it would return False. 我必须创建一个接受2个字符串并使用递归的函数,以查看第一个字符串中的元素是否在第二个字符串中,如果是,则返回true,否则返回false说“ Carpool”和“ prlo”或“ elephant”和“ xph”,在第一种情况下,递归参数将返回True,在第二种情况下,它将返回False。

This is what I've been trying to do. 这就是我一直试图做的。 I set a count so that if the elements match I can increase it and at the end if it's equal to len(str2) then I print 2. The major problem is iterating through the 2 strings separately, any idea on how I should approach this? 我设置了一个计数,以便如果元素匹配我可以增加它,最后如果它等于len(str2)则我打印2。主要问题是分别遍历两个字符串,关于如何处理此问题的任何想法?

def compare(str1,str2): def compare(str1,str2):

count = 0
if str1 == str2:
    return "True"           
elif str1[0] == str2[0]:
    count = count + 1
    return letCheck (str1[1:],str2)
elif str1[0] != str2[0]:
    return letCheck (str1[1:],str2)
def compare(s1, s2):
    if not s2:
        return True
    elif s2[0] in s1:
        return compare(s1, s2[1:])
    else:
        return False

On your examples: 在您的示例中:

>>> compare( "Carpool" , "prlo")
True
>>> compare("elephant", "xph")
False

How it works 这个怎么运作

The function processes each character in string 2, s2 , one at a time. 该函数一次处理字符串2 s2每个字符。 There are three cases: 有以下三种情况:

  1. If there are no characters left to process in s2 , that means that all the tests have passed and we return True. 如果s2中没有要处理的字符,则意味着所有测试均已通过,并且我们返回True。

  2. If there are still characters left in s2 , then we test s2[0] . 如果s2中还剩下字符,则我们测试s2[0] If it passes, we then use recursion to test the rest of the string. 如果通过,则使用递归测试其余的字符串。

  3. If s2[0] is not in s1 , then we have a fail and we return False. 如果s2[0]不在s1 ,则我们将失败并返回False。

You don't need a counter. 您不需要柜台。 You can just check if the first letter of the first String (str1) is in the second string (str2). 您可以只检查第一个字符串(str1)的第一个字母是否在第二个字符串(str2)中。 If so, then check if this was the last character of the first string. 如果是这样,则检查这是否是第一个字符串的最后一个字符。 If it wasn't the last character, pass the rest of the string to the function again (recursion). 如果不是最后一个字符,则将字符串的其余部分再次传递给函数(递归)。 And if one character of the first string is not in the second one, you return False. 并且如果第一个字符串的一个字符不在第二个字符串中,则返回False。

def compare(str1, str2):
    if str1[0] in str2:
        if len(str1) == 1:
            return True;
        return compare(str[1:0], str2);
    else:
        return False;

print compare('ak', 'abcd');  # False
print compare('cd', 'abcd');  # True
print compare('efgh', 'efg'); # False   

This will return False if str2 is passed in as an empty string: 如果将str2作为空字符串传递,则将返回False:

def letCheck(str1, str2, count = 0):
    if str1 == str2: # both strings are equal,we don't have to  go any further
        return True
    elif str2 == "" and count == 0: # if str2 is empty and count is 0 we got passed an empty str2
        return False
    elif len(str2) == count: # if count and len are equal, all str2 letters are in str1
        return True
    elif str2[0] in str1:
        count += 1 # increase count and move to the next letter in str2[1:]
        return letCheck(str1, str2[1:],count)
    return False # if we get here we have found a letter that is not in str1

When using a variable like count , you need to use it as a parameter to keep the value between each recursive call or else it will get reset to 0 each call. 当使用诸如count类的变量时,您需要将其用作参数以保持每次recursive调用之间的值,否则它将在每次调用时重置为0

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

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