我正在嘗試創建一個 Python 函式,該函式決議二叉樹的括號表示并輸出它的逐行二分圖表示,其中磁區由“|”分隔,因此:
二叉樹括號表示:
(((A B C D)
二分圖關系輸出:
AB | 光碟
美國廣播公司 | D
我使用遞回來處理它,在串列中維護每個二分關系線,將原始括號符號字串和決議的起始索引作為輸入。
def makeBipartRecursive(treeStr, index):
bipartStr = ""
bipartList = []
for ind, char in enumerate(treeStr, start=index):
if char == '(':
# Make recursive call to makeBipartRecursive
indx = ind
bipartList.append(makeBipartRecursive(treeStr, indx 1))
elif char == ')':
group1 = treeStr[0:index-1] treeStr[ind 1::]
group2 = treeStr[index:ind]
return group1 " | " group2
elif char == ',':
bipartStr = " "
else:
# Begin construction of string
bipartStr = char
每次遇到開括號時,都會進行遞回呼叫,從緊跟開括號的索引處開始列舉,以防止無限遞回(或者我認為)。如果可能的話,盡量忽略我實際上并沒有回傳串列的事實。主要問題是我遇到了無限遞回,其中列舉永遠不會超出字串中的第一個字符。我的遞回呼叫是否應該使用遞增的列舉起始位置來解決這個問題?
提前致謝。
uj5u.com熱心網友回復:
您誤解了start引數 of的使用enumerate。這并不意味著從這個位置開始列舉,而是從這個索引開始計數。見help(enumerate):
| The enumerate object yields pairs containing a count (from start, which
| defaults to zero) and a value yielded by the iterable argument.
因此,基本上每次執行遞回呼叫時,您都會從字串的開頭重新開始。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442120.html
