Python最大递归深度达到错误

时间:2014-09-28 02:54:21

标签: python recursion

所以我在这里得到的是一系列函数,用于搜索字符串中的目标值 (例如:在$&(*,。02468:<> @BDFHJLNPRTVXZ \ ^`bdfhj中找到R,在索引18处找到H。)

但是当对某些字符执行该函数的测试时,它可以正常工作但对于其他一些字符(例如D或L)它会给我 "最大递归深度达到错误&#34 ; 即可。

对于前面的字符,例如$ in&(,。02468:<> @BDFHJLNPRTVXZ \ ^`bdfhj,结果为 "无法找到" *

作为python中的新手,我很难看到这些函数出了什么问题,所以这里似乎有什么问题?

EDIT ---------

很抱歉我的意思很混乱导致最大递归深度错误的函数似乎有什么问题,以及我应该如何开始测试这些函数。

def str_search( data, target, start, end ):

"""
str_search : String String NatNum NatNum -> NatNum or NoneType
Description:
Search for a target value in a sorted data string.
The search happens between the start and end indices inclusively.
This starts searching in the middle. If it finds the target, it is done.
Otherwise it decides whether to search the first half or the second half.
preconditions: the data string is in ascending alphanumeric order.
Parameters:
    data - a string
    target - the target value to find is a single character string e.g. 'Q'
    start - the starting index into the data
    end - the ending index into the data
Returns:
    index of target in data, if present; otherwise None.
"""

    if start == end:
        return None

    mid_index = ( start + end ) // 2
    mid_value = data[mid_index]

# debug statement prints the data.
#print( "Searching for", target, ":", data[start:mid_index], 
#    "*" + str( mid_value ) + "*", data[mid_index+1:end+1] )

    if target == mid_value:
        return mid_index
    elif target < mid_value:
        return str_search( data, target, start, mid_index-1 )
    else:
        return str_search( data, target, mid_index, end )

def find_target( data, target ):
"""
find_target : String String -> NatNum or NoneType
find_target returns the index of target in data or None if not found.
Parameters:
    data - a string
    target - the target value to find
Returns:
    The index of the target element in data, if present, or None.
"""

    return str_search( data, target, 0, len( data ) - 1 )

def makeString():
    """
    makeString : () -> String
    makeString returns a String
    """
    data = ""
    # append characters to make the string
    for num in range( 36, 108, 2 ):
        data += chr( num )
    return data

def main_search():
    """
    main_search : Void -> NoneType
    """

    data = makeString()
    print( "Number of elements: ", len( data ) )

    while True:
        print( "\nData: ", data )
        target = input( "Enter a character to find: " )

        if target == "":
            break
        else:
            index = find_target( data, target )
            print()
            if index != None:
                print( target, "found at index", index )
            else:
                print( target, "not found" )
# end while

2 个答案:

答案 0 :(得分:1)

str_search 功能有两个问题。

  1. 以下代码在$处于开头时失败。您的搜索最终会转到(start,end)=(0,0),然后start == endTrue,返回None

    if start == end:
        return None
    
  2. 当您搜索“D”时,更大的问题是您在下面的代码中进入无限递归循环。当您搜索D时,您的开始和结束将关注(0,35)(0,16)(8,16)(12,16)(14,16)(15,16),{ {1}} ....的无限 !!!

    (15,16)
  3. 我相信上述1和2的修复都可以通过处理elif target < mid_value: return str_search( data, target, start, mid_index-1 ) 的情况来完成。

    删除以下行:

    end - start=1

    替换为:

    if start == end:
        return None
    

    在没有输入输入的情况下进行测试的快速样本方式是:

    if (end - start == 1):
        if target == data[end]:
            return end
        elif target == data[start]:
            return start
        else:
            return None
    

    但是如果你想进行彻底的测试,最好使用python单元测试并使用断言。请参阅此处的文档:https://docs.python.org/2/library/unittest.html

答案 1 :(得分:0)

这对字符串中包含的字符没有错误:

if target == mid_value:
    return mid_index
elif target == data[mid_index+1]:
    return mid_index+1
elif target < mid_value:
    return str_search( data, target, start, mid_index )
else:
    return str_search( data, target, mid_index, end )

内置python功能:

data = "something"
index_of_chr_in_string = data.find("m")
# or
print("something".find("t"))