Python 递归查找元素是否属于列表

Python 递归查找元素是否属于列表,python,algorithm,list,recursion,Python,Algorithm,List,Recursion,假设我有一个列表x=[1,2,3,4,5,3,4] 是否有任何递归方法来查找元素a(假设a=3)是否在列表中,只使用条件(如果不是x:)和指令list.pop([i])?类似于: def find(x,index): if index == len(array): return False; if array[index] != x: find(x,index + 1) else: return array.pop([index])

假设我有一个列表
x=[1,2,3,4,5,3,4]

是否有任何递归方法来查找元素
a
(假设
a=3
)是否在列表中,只使用条件
(如果不是x:
)和指令
list.pop([i])

类似于:

def find(x,index):
   if index == len(array):
       return False;
   if array[index] != x:
        find(x,index + 1)
   else:
        return array.pop([index])

定义一个函数,如:

def search(lst, key):
    if not lst:         # base case: list is empty
        return False
    elif lst[0] == key: # base case: current element is searched element
        return True
    else:               # recursive case: advance to next element in list
        return search(lst[1:], key)
然后调用
search(x,a)

更新:如果要使用pop实现此功能,只需使用lst.pop()更改行lst[0]和lst[1:]

使用以下命令:

def find(test_list,element):
 try: 
  z=test_list.pop(0)    
  if element==z:
     return True
  return find(test_list,element)
 except IndexError:    
  return False

没有任何<代码>用于<代码>或<代码>而<代码>?是的,有。。递归地。提示:在递归调用方法之前,弹出一个项。由于
pop
删除了最右边的元素,如果您不能使用
len(lst)
(或
lst[-1]
),您还需要首先接受一个
i
,然后提供一个
i
,每个递归调用递减一次,因此
lst[i]
指的是最后一个元素。这似乎是对家庭作业的约束。。。你应该自己做。我可以弹出它,并将其与
a
进行比较,但在程序结束时,我会打印每次比较,而不是最终打印。那么你的代码在哪里,它到底有什么问题?我想OP最初使用
list.pop([I])
的要求是错误的。可能是
lst.pop()
lst[i]
,这更有意义。虽然这是一种更好的操作选择方法,但它不使用
pop
[i]
——这可能分别意味着
lst.pop()
lst[i]
。家庭作业问题是。。愚蠢。这确实是一种方法,但我不允许再做一次比较,除了
如果不是lst:
@TBone如果你确定列表不是空的,那么就不要使用那一行(坏习惯)@user2864740使用
pop
应该尝试例如
lst.pop(0)
而不是
lst[0]
。由于
pop(0)
是线性的,那么最好使用
pop()
@TBone,如果您想使用
pop
实现此功能,只需将行
lst[0]
lst[1://code>更改为
lst.pop()
,这就是我想要的答案……谢谢!
def find(test_list,element):
 try: 
  z=test_list.pop(0)    
  if element==z:
     return True
  return find(test_list,element)
 except IndexError:    
  return False