如何找出python中表達式的深度?我寫的代碼很適合像[[1,2],[1,2,[3,6,54]]
輸入,而不是那些象depth (['+', ['expt', 'x', 2], ['expt', 'y', 2]]) => 2
和depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
使用Python表達式的深度
a=0
k=0
j=0
maxli=[]
li =[[1,2],[1,2,[3,6,54]] # list whose depth is to be found
#print len(li)
def depth(x):
global a,k,j
j=j+1
print" j's value is ",j
for i in x:
for h in range(len(li)): # runs loop through the items of the list
if i== li[h] : k=0
if isinstance(i,(tuple,list)) == True: #if we find that there is list
k=k+1
# print "this is for item",i
# print k
depth(i)
a=k
maxli.append(a) # putting the values of a in maxli
depth(li)
print "The depth of tree is :",max(maxli)
可能重複[計數「深度」或最深層次的嵌套列表去(http://stackoverflow.com/questions/6039103/counting-deepness-或最深層次的嵌套列表去) –
在我的代碼我有深入的地方的FN,我忘了編輯它之前發佈在這裏.. –