简体   繁体   中英

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. I had used a while loop but that hadn't work and neither does a generic if statement

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

I would suggest instead of passing a new list every time( by slicing the list), pass same list and update the counter value.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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