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
>>> 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]
582 PHP ssh2_scp_send fails to send files as intended
918 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
621 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.