best way to check if a list does or does not contain a series of values in the same order? (python)
Question:
I need a function that takes a list and checks if ['x','y','z']
is in
/not in
that list in the exact same order.
For example:
list = ['_','x','y','z','_']
if ['x','y','z'] """not""" in list: # `not in` is the actual format of function but commented out to make example easier to explain
return True
else:
return False
I want:
- If the list is
[,'_','x','y','z','_']
, then return True
- If the list is
[,'_','x','y','a','_']
, then return False
- If the list is
[,'_','x','z','y','_']
then return False
etc.
(Note: the not
is commented out because the actual function should return True if ['x','y','z'] not in list:
but it is easier to explain without the not
condition.)
Answers:
if you merge your list into a string using the .join() function you could then simply write:
if 'xyz' not in string:
return true
def your_function(list_of_chars):
return "xyz" in "".join(list_of_chars)
your_list = ['_','x','y','z','_']
your_function(your_list) # == True
list = ['_','x','y','z','_']
order = ['x','y','z']
def f(l,o):
i=0
j=0
while i<len(l) and j<len(o) :
if(l[i]==o[j]):
i+=1
j+=1
else:
i+=1
else:
if j==len(o):
return True
else:
return False
print(f(list,order))
You can use this algo for your task.It loop thtough both order and list and check whether order in there.
I need a function that takes a list and checks if ['x','y','z']
is in
/not in
that list in the exact same order.
For example:
list = ['_','x','y','z','_']
if ['x','y','z'] """not""" in list: # `not in` is the actual format of function but commented out to make example easier to explain
return True
else:
return False
I want:
- If the list is
[,'_','x','y','z','_']
, then return True - If the list is
[,'_','x','y','a','_']
, then return False - If the list is
[,'_','x','z','y','_']
then return False
etc.
(Note: the not
is commented out because the actual function should return True if ['x','y','z'] not in list:
but it is easier to explain without the not
condition.)
if you merge your list into a string using the .join() function you could then simply write:
if 'xyz' not in string:
return true
def your_function(list_of_chars):
return "xyz" in "".join(list_of_chars)
your_list = ['_','x','y','z','_']
your_function(your_list) # == True
list = ['_','x','y','z','_']
order = ['x','y','z']
def f(l,o):
i=0
j=0
while i<len(l) and j<len(o) :
if(l[i]==o[j]):
i+=1
j+=1
else:
i+=1
else:
if j==len(o):
return True
else:
return False
print(f(list,order))
You can use this algo for your task.It loop thtough both order and list and check whether order in there.