pProblem在函数中具有递归和范围(Python)

时间:2016-11-26 00:18:22

标签: python-3.x recursion

这段代码应该带一个字符串并返回一个没有重复字符的字符串(不是" aa"," bb","" 55&#34 ;等)。它通过递归工作:函数调用自身,细化字符串直到它没有重复,但然后它返回原始字符串。我无法理解如何修复它。代码如下,抱歉,如果这个问题太过琐碎,但对我来说不是。谢谢您的考虑。 (并且抱歉"黑客攻击"标题格式化)

def removeRepetitions(s):
    result=""
    for i in range(len(s)-1):
        if len(s)!=1 and s[i]==s[i+1]:
            result=s[:i+1]+s[i+2:]
            removeRepetitions(result)
            return result

2 个答案:

答案 0 :(得分:1)

如果缩进正确,则返回值的缩进不正确,并且您没有分配递归函数的return。您还需要在开头指定results而不是空字符串。您的终端案例必须返回s中的单个字符:

def removeRepetitions(s):
    result = s
    for i in range(len(s)-1):
        if len(s)!=1 and s[i]==s[i+1]:
            result = removeRepetitions(s[:i+1]+s[i+2:])
    return result

>>> removeRepetitions('Mississippi')
'Misisipi'

但是你似乎在混合递归和迭代解决方案,更加递归的解决方案不需要for循环:

def removeRepetitions(s):
    if len(s) <= 1:
        return s
    c, s = s[0], removeRepetitions(s[1:])
    if c == s[0]:
        return s
    return c+s

>>> removeRepetitions('Mississippi')
'Misisipi'

答案 1 :(得分:1)

你缺少的主要内容是返回陈述以涵盖所有可能性。您也不需要中间变量result。纠正缩进后:

def removeRepetitions(s):
    for i in range(len(s) - 1):
        if s[i] == s[i+1]:  # found a dup!
            # Assemble a return value by taking everything prior to the
            # duplicate (which is duplicate free) and concatenating the
            # result of removing duplicates from the remainder of the
            # input string, excluding the first of the duplicated chars
            return s[:i] + removeRepetitions(s[i+1:])
    return s  # return input string if we made it through w/o any duplicates

print(removeRepetitions("aaaabccdddeee"))    # => "abcde"

另请注意,对于最终的return语句,检查len(s)!=1是无关紧要的。