简体   繁体   English

递归查找列表中的相同数字

[英]Recursively finding the same numbers in a list

I've been wanting to practice my python and so I want to be able to locate the number 3 using recursion but the code itself continues to run past the number of elements in the list.我一直想练习我的 python,所以我希望能够使用递归找到数字 3,但代码本身继续运行超过列表中的元素数量。 I had used a while loop but that hadn't work and neither does a generic if statement我使用了一个while循环,但这不起作用,通用if语句也没有

listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x,counter):
if counter >= 0:
    if x[0] == 3:
        print("here")
        recursion(x[1:],len(x)-1)
    else:
        print("next item...")
        recursion(x[1:],len(x)-1)
else:
    return "Done"

It does find 3 both times, but the code is in an endless loop它确实找到了 3 次,但代码处于无限循环中

I would suggest instead of passing a new list every time( by slicing the list), pass same list and update the counter value.我建议不要每次都传递一个新列表(通过切片列表),而是传递相同的列表并更新counter值。

listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x, current_index=0):
    if current_index >= len(x):  # base condition
        return
    if x[current_index] == 3:
        print("Got 3 at:", current_index)
    recursion(x, current_index+1)

You need to return the counter when you find 3, otherwise, slice the list and continue.找到 3 时需要返回计数器,否则,切片列表并继续。

listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x,counter):
    if counter > 0:
        if x[0] == 3:
            return counter
        else:
            print("next item...")
            return recursion(x[1:],len(x)-1)
    else:
        return -1
res = recursion(listofnum, len(listofnum))
print(res)

It's not clear how you invoke your recursion function, but I guess it's in form like:目前尚不清楚您如何调用递归函数,但我猜它的形式如下:

recursion(listofnum, len(listofnum))

In my case, trying your code, it correctly stops with an在我的情况下,尝试您的代码,它正确地以

IndexError: list index out of range error IndexError:列表索引超出范围错误

because of the " counter >= 0 " condition, which makes your code attempting to read on position 0 even if the supplied list has no elements at all, thus no 0 (first) position does exist.由于“ counter >= 0 ”条件,即使提供的列表根本没有元素,这也会使您的代码尝试在位置0上读取,因此不存在 0(第一个)位置。

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

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