【发布时间】:2022-01-22 14:38:51
【问题描述】:
我正在尝试使用此函数来检查列表 SEQUENCE 是否是列表 ARRAY 的子序列。子序列的意思是:必须有所有的数字,并且它们必须是相同的顺序。在下面的示例中,SEQUENCE 是 ARRAY 的子序列。 数组=[5, 1, 22, 25, 6, -1, 8, 10] 序列= [1, 6, -1, 10]
谁能告诉我为什么我的代码不起作用?
array=[5, 1, 22, 25, 6, -1, 8, 10]
sequence= [1, 6, -1, 10]
def isValidSubsequence(array, sequence):
arrayValid=[]
if len(array) >= len(sequence):
for i in range(len(sequence)):
numSeq = sequence[i]
for j in range(i, len(array)):
numArr = array[j]
if numSeq==numArr:
arrayValid.append(numArr)
array.remove(numArr)
else:
array.remove(numArr)
if arrayValid==sequence:
return True
else:
return False
else:
return False
【问题讨论】:
标签: python for-loop append sequence