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