我正试图获得一棵树的深度。 以下是我的代码:
def getTreeDepth(myTree):
maxDepth = 0
firstStr = list(myTree.keys())[0]
secondDict = myTree[firstStr]
for key in list(secondDict.keys()):
if type(secondDict[key]).__name__ == 'dict':
thisDepth = 1+ getTreeDepth(secondDict)
else:
thisDepth = 1
if thisDepth > maxDepth: maxDepth = thisDepth
return maxDepth
然而,当我运行它时:
myTree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
getTreeDepth(myTree)
<ipython-input-54-d4442919fa4f> in getTreeDepth(myTree)
17 firstStr = list(myTree.keys())[0]
18 secondDict = myTree[firstStr]
---> 19 for key in list(secondDict.keys()):
20 if type(secondDict[key]).__name__ == 'dict':
21 thisDepth = 1+ getTreeDepth(secondDict)
AttributeError: 'str' object has no attribute 'keys'
如何在不更改此算法的情况下更正它?
非常感谢!
答案 0 :(得分:0)
myTree = {
'no surfacing': {
0: 'no',
1: {
'flippers': {
0: 'no',
1: 'yes'}}}}
def myTreeDepth(myTree): maxDepth = 0 for value in myTree.values(): if type(value) == type({}): thisDepth = 1 + myTreeDepth(value) else: thisDepth = 1 if thisDepth > maxDepth: maxDepth = thisDepth return maxDepth print('maxDepth =', getTreeDepth(myTree))
给出:
maxDepth = 4
注意:
字典的.keys()
方法返回一个iterable,因此不需要将返回的值转换为列表以便迭代它。这同样适用于.values()
和.items()
检查字典树深度的迭代在字典.values()
而非.keys()
上运行。如果您想使用整个字典条目,可以使用for key, value in dict.items()
您正在使用的算法中不需要firstStr = list(myTree.keys())[0]
和secondDict = myTree[firstStr]
。