简体   繁体   English

递归的新手,找不到解决方案

[英]new to recursion, can't find solution

I'm supposed to get those results, the first two strings are the s1 and s2 and the third one is the result i should get. 我应该得到那些结果,前两个字符串是s1和s2,第三个是我应该得到的结果。 The first code is the one i wrote and the second one is the teacher's. 第一个代码是我编写的代码,第二个代码是老师的代码。

“Maria” e “Norma”: Mnao |
“Mai” e “Nor”: Mnaoir   |
“Maria” e “Noa”:False   |
“Mar” e “Noa”: MNaora   |
“Mar” e “Noar”: False
def strin(s1,s2):
    count_n(s1,s2)
    if len(s1)==len(s2) or s1[n]==s2[n]:
        if s1[0]==s2[0]:
            return ""
        else:
            return s1[0]+s2[0]+strin(s1[1:],s2[1:])
    else:
        return False



def count_n(s1,s2):
    global n
    n=0
    if len(s1)==len(s2) and (len(s1)>0 or len(s2)>0):
        if s1[0]==s2[0]:
            return n
        else:
            return (n+1) and count_n(s1[1:],s2[1:])
    else:
        return n

teacher's answer 老师的回答

def intercala( s1,s2): def intercala(s1,s2):

if s1=='' and s2 == '':
     return ''
if s1=='' or s2 =='':
    return  False
if s1[0] == s2[0]:
    return ''

resp= intercala(s1[1:], s2[1:])
if resp != False:
    return s1[0]+s2[0]+resp
else:
    return resp

def intercala2(s1,s2): def intercala2(s1,s2):

if s1=='' and s2 == '':
     return ''
if s1=='' or s2 =='':
    return False
if s1[-1] == s2[-1]:
    return intercala2(s1[0:-1],s2[0:-1])

resp= intercala(s1[0:-1], s2[0:-1])
if resp != False:
    return resp + s1[-1]+s2[-1]
else:
    return resp

hey guys i found a answer, thanks for the help 嘿,我找到了答案,谢谢您的帮助

def recur(s1,s2):
if len(s1)==len(s2):
    if s1[0]==s2[0]:
        return ""
    if len(s1)==1 or len(s2)==1:
        return s1[0]+s2[0]
    else:
        return s1[0]+s2[0]+recur(s1[1:],s2[1:])
else:
    return False

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

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