简体   繁体   English

使用 python 递归查找元素的深度

[英]Find depth of element with recursion using python

My task is to find depth of an element.我的任务是找到一个元素的深度。 I cannot change function depth in MAIN (this: depth('g', ['a', ['b', 'c', 'd'], ['e', 'f']]) ).我无法更改 MAIN 中的 function 深度(此:depth('g', ['a', ['b', 'c', 'd'], ['e', 'f']]) )。 Firs I want to find depth without recursion but I get wrong result.杉木我想在没有递归的情况下找到深度,但我得到了错误的结果。 I tried with increment level but it returned 6 in this particular test case.我尝试使用增量级别,但在这个特定的测试用例中它返回 6。

def depth(x, L):
    level = 0
    if not L:
        return 0;
    for i in range(len(L)):
        for j in L[i]:
            if x == j:
                return i
            else:
                continue
    
if __name__ == '__main__':
    depth('g', ['a', ['b', 'c', 'd'], ['e', 'f']])
    depth('d', ['a', ['b', 'c', 'd'], ['e', 'f']])

For these 2 cases result should be:对于这两种情况,结果应该是:

  1. Element g is not in the list元素 g 不在列表中
  2. Depth of an element d is 2元素的深度 d 为 2

EDIT try with recursion:编辑尝试递归:

def depth(x, L):
    level = 0
    if not L:
        return 0
    for i in range(len(L)):
        if x == L[i]:
            return i
        else:
            depth(x,L[i+1])

I'll focus on the recursive attempt, as it shows immediate problems:我将专注于递归尝试,因为它显示了直接的问题:

...
for i in range(len(L)):
    if x == L[i]:
        return i
    else:
        depth(x,L[i+1])

First, when you do find the item, you return its position in the list.首先,当您找到该项目时,您在列表中返回其 position。 This has nothing to do with its depth in the nesting.这与它在嵌套中的深度无关 For instance, if you search for b, c, d in three separate calls, your base case returns three different values (0, 1, 2) for them, even though they're at the same level.例如,如果您在三个单独的调用中搜索b, c, d ,您的基本情况会为它们返回三个不同的值(0、1、2),即使它们处于同一级别。 This guarantees a wrong answer.这保证了错误的答案。

Instead, you need to return 1 or 0 from your base case (depending on how you count the depth), and then simply add 1 at each level as you work back up the tree:相反,您需要从基本情况中返回 1 或 0(取决于您如何计算深度),然后在备份树时只需在每个级别添加 1:

for i in range(len(L)):
    if x == L[i]:
        return 1   # ... or 0
    else:
        depth(x, ...) + 1

This will be more clear if you iterate through the elements, rather than the indices:如果您遍历元素而不是索引,这将更加清楚:

for item in L:
    if x == item:

Even more pressing is that when you do any recursion, you fail to return a value, so you'll get a result of None .更紧迫的是,当您进行任何递归时,您无法返回值,因此您将得到None的结果。 Simply calling a function doesn't return the desired value.简单地调用 function 不会返回所需的值。 That last clause needs to be最后一个条款需要是

    else:
        return depth(x, ...) + 1

Finally, when you recur, you must do so iff the item is a list:最后,当您重复时,如果项目是列表,则必须这样做:

for item in L:
    if isinstance(L, list):
        found = depth(x, item)
        if found is not None:
            return found + 1
    elif x == item:
        return 1
def depth_helper(find, nested_list):
    if find == nested_list:
        return 0
    else if type(find) == type([]) and find:
        return 1 + min((depth_helper(find, element) for element in find))
    else:
        return float('inf')

def depth(find, nested_list):
    result = depth_helper(find, nested_list)
    if result == float('inf'):
        print(f"Element {find} is not in the list")
    else:
        print(f"Depth of an element {find} is {result}")

We factor out the computation of the depth as a pure helper function.我们将深度的计算分解为纯辅助 function。

I already said that i cannot change calling function我已经说过我不能更改调用 function

If you cannot change it, how are you expected to make it work?如果你不能改变它,你希望如何让它发挥作用? It's obvious by the two varying attempts of depth that you are able to change it to solve the problem.很明显,通过两次不同的depth尝试,您可以更改它来解决问题。 Anyway, I reordered my original answer so the outermost function name is depth -无论如何,我重新排序了我的原始答案,所以最外面的 function 名称是depth -

def depth(x, L):
  def find(d, t):
    if isinstance(t, list):
      for v in t:
        yield from find(d + 1, v)
    else:
      yield (t, d)
  for (v, d) in find(0, L):
    if v == x:
      return d
print(depth('g', ['a', ['b', 'c', 'd'], ['e', 'f']]))
print(depth('d', ['a', ['b', 'c', 'd'], ['e', 'f']]))

Results -结果 -

None
2

Isolating concerns makes your code easier to read/write and promotes reuse within other areas of your program.隔离关注点使您的代码更易于阅读/编写,并促进在程序的其他区域内重用。

I think that this question comes from some kind of homework, my tips is trying to understand why something isn't working the way we want, go through the studying material again first and then ask for help to strangers我认为这个问题来自某种家庭作业,我的提示是试图理解为什么有些事情没有按照我们想要的方式工作,go 先通过学习材料再向陌生人寻求帮助

"Everybody should learn to program a computer, because it teaches you how to think.” “每个人都应该学习编程计算机,因为它教你如何思考。”

Anyway just some advice:无论如何只是一些建议:

  1. the var level that you create and never use您创建但从不使用的 var level

  2. As pointed out by martin range starts from 0正如马丁所指出的,范围从 0 开始

  3. I don't understand the first if block, maybe you meant something like:我不明白第一个 if 块,也许你的意思是:

     if x not in L
  4. The recursion version has some core problems but I'll let you figure out by your self!递归版本有一些核心问题,但我会让你自己弄清楚!

def depth(x, L):
    for i in range(len(L)):
        for j in L[i]:
            if x == j:
                return i + 1
    return "Not present"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM