To output a list of Python recursive function utilization index values

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

The code I made is

listn=[] #emptylist  
def searchn(list, key): #searchn function definition

    for n in range (len(list)):
        if list[n]==key:
            listn.append(n)
    print(listn) 

Like this, let the for statement rotate by Len of the list valueWell. The [n] value of the list (index value) is stored in the new list, listn.

How can I express this as a recursive function?

python list recursive

2022-09-20 10:48

1 Answers

>>> l = [ 1, 2, 3, 4, 5 ]
>>> def searchn(l, k, offset=0):
    if len(l) == 1:
        ilist = []
        if l[0] == k:
            ilist.append(0+offset)
        return ilist
    if l[0] == k:
        return [ offset ] + searchn(l[1:], k, offset+1)
    return searchn(l[1:], k, offset+1)

>>> searchn(l, 3)
[2]
>>> l = l+l+l
>>> searchn(l, 3)
[2, 7, 12]
>>> def searchn(l, k, offset=0):
    if len(l) == 0:
        return []
    if l[0] == k:
        return [ offset ] + searchn(l[1:], k, offset+1)
    return searchn(l[1:], k, offset+1)

>>> searchn(l, 3)
[2, 7, 12]
>>> searchn([1,3,3,3,3], 3)
[1, 2, 3, 4]


2022-09-20 10:48

If you have any answers or tips


© 2022 pinfo. All rights reserved.