所以我在這裏得到了一系列搜索字符串中的目標值的函數。
(例如:在$ &(找到R * ,. 02468:<> @BDFHJLNPRTVXZ \ ^`bdfhj,H在索引18)Python最大遞歸深度達到了錯誤
但是發現當用於功能測試是爲某些字符執行它工作正常,但對於其他一些國家(如d或L)它給我的「最大遞歸深度達到了錯誤」。
也爲前面的字符,如$在$ &(。 02468:<> @BDFHJLNPRTVXZ \ ^`bdfhj,結果是「it ca找不到「*
作爲python的新手,我很難看出這些函數有什麼問題,所以這裏看起來有什麼問題呢?
編輯---------
對不起,我的意思是的混亂似乎是在錯誤的造成最大遞歸深度錯誤,我應該如何開始測試這些功能的功能。
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
嘛,你明明知道要插入一些調試打印語句,所以調試輸出在什麼時候與預期的不同? – 2014-09-28 03:10:48
您在這裏提出多個問題。你想要哪一個答案?如果它是最後一個,那就是「看起來似乎錯了」,這對於StackOverflow來說太廣泛了。如果是關於最大遞歸深度,這很容易(Python不允許無限遞歸,並且不會執行尾調用消除,因此您不能使用遞歸算法,其深度可能接近1000),但幾乎肯定是重複的。如果是關於其他事情,請特別告訴我們您需要解決的問題。其他的東西使得很好的背景細節,但我們仍然需要知道實際的問題。 – abarnert 2014-09-28 03:12:36
無論如何,即使沒有閱讀你的代碼,我願意你有一個錯誤的錯誤。這在對分算法中很容易實現。查看stdlib的'bisect'模塊的源代碼(鏈接自[文檔](https://docs.python.org/3/library/bisect.html);閱讀和理解相當容易,重新嘗試做同樣的事情,應該很容易看到(通過檢查或打印出調試信息)您正在發生的錯誤。 – abarnert 2014-09-28 03:14:57