递归函数,它接受两个str返回一个排序的str

时间:2016-10-31 05:13:37

标签: python recursion

def merge_chars(a : str, b : str) -> str:
    if a == '':
        return b
    if b == '':
        return a

    for x in a:
        for y in b:
            if x > y:
                return y + merge_chars(a[1:],b)
            elif x < y:
                return x + merge_chars(a,b[1:])

此函数接受两个str,并按字母顺序返回str。例如:

 merge_chars('abxy','lmz') 

返回

'ablmxyz'.

使用递归是必需的。

然而,当我的函数调用

merge_chars('ace','bdf')

它返回

aaaace

而不是

abcdef

我得到的错误如下:

39 # Test merge_chars
43 *Error: merge_chars('ace','bdf') -> aaaace but should -> abcdef
44 *Error: merge_chars('abc','xyz') -> aaaabc but should -> abcxyz
45 *Error: merge_chars('abxy','lmzzz') -> aaaaaabxy but should -> ablmxyzzz
46 *Error: merge_chars('acdeghilmnosu','bfjkpqrtvwxyz') -> aaaaaaaaaaaaaacdeghilmnosu but should -> abcdefghijklmnopqrstuvwxyz
47 *Error: merge_chars('bcgprvyz','adefhijklmnoqstuwx') -> aaaaaaaaadefhijklmnoqstuwx but should -> abcdefghijklmnopqrstuvwxyz
48 *Error: merge_chars('cdefghijklmnpqrstuvw','aboxyz') -> aaaaaaaaaaaaaaaaaaaaaboxyz but should -> abcdefghijklmnopqrstuvwxyz
51 *Error: merge_chars(''.join(sorted(l[:13])), ''.join(sorted(l[13:]))) -> aaaaaaaaaaaaaabcdgjlnpqrtz but should -> abcdefghijklmnopqrstuvwxyz

有人可以告诉我如何解决它吗?

1 个答案:

答案 0 :(得分:1)

如果要使用递归,则不需要使用循环。相反,只需在每次调用中删除一个字符,然后递归。您只需确保涵盖以下三种方案中的每个方案:

  1. 两个字符串都没有留下字符
  2. 只有一个字符串有字符
  3. 两个字符串都有字符
  4. 以下是示例:

    def merge_chars(a, b):
        # Base case
        if not a and not b:
            return ''
    
        if a and (not b or a[0] <= b[0]):
            return a[0] + merge_chars(a[1:], b)
        else:
            return b[0] + merge_chars(a, b[1:])
    
    CASES = [
        ('ace', 'bdf'),
        ('abc', 'xyz'),
        ('abxy', 'lmzzz'),
        ('acdeghilmnosu', 'bfjkpqrtvwxyz'),
        ('bcgprvyz', 'adefhijklmnoqstuwx'),
        ('cdefghijklmnpqrstuvw', 'aboxyz')
    ]
    
    for x, y in CASES:
        print('{} & {} -> {}'.format(x, y, merge_chars(x, y)))
    

    输出:

    ace & bdf -> abcdef
    abc & xyz -> abcxyz
    abxy & lmzzz -> ablmxyzzz
    acdeghilmnosu & bfjkpqrtvwxyz -> abcdefghijklmnopqrstuvwxyz
    bcgprvyz & adefhijklmnoqstuwx -> abcdefghijklmnopqrstuvwxyz
    cdefghijklmnpqrstuvw & aboxyz -> abcdefghijklmnopqrstuvwxyz