【问题标题】:Depth of an expression using Python使用 Python 的表达式的深度
【发布时间】:2015-12-09 08:12:58
【问题描述】:

如何在 python 中找出表达式的深度?我编写的代码适用于[[1,2],[1,2,[3,6,54]] 之类的输入,但不适用于depth (['+', ['expt', 'x', 2], ['expt', 'y', 2]]) => 2depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4 之类的输入

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)

【问题讨论】:

标签: python-2.7


【解决方案1】:

这里使用递归的正确方法是通过函数的返回值,而不是通过操作全局变量。您可以像这样定义深度函数:

def is_list(x):
    return hasattr(x,'__getitem__') and type(x) != str

def depth(l):
    if not is_list(l): return 0
    maxdepth = 0
    for elem in l:
        maxdepth = max(maxdepth, depth(elem))
    return maxdepth + 1

【讨论】:

  • 事实证明,它确实使用了递归。原帖中的fn 应该是函数名称depth
猜你喜欢
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 2016-07-24
  • 1970-01-01
相关资源
最近更新 更多