0
def list(small,big):
    for i in range(len(big)):
        if small[i]!=big[i]:
            break

    else:
        return False

hi, i am new to python. I want to find if the numbers in a list are in another list. so [7,8,4] and [8,5,1] are subsequence of [7,8,5,4,1] and should return True, but [7,8,8] and [7,1,8] are not and should return False.

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
hrk23
  • 23
  • 6

3 Answers3

0

something like this would work Since you are a newbie and building on your function idea

def lister(small,big):
    for i in range(len(small)):
        if small[i] not in big:
            return False
    return True

print(lister([1,2,3],[1,2,3,4,5]))

define your function as lister since list is already a built in function in python

Edit: to Find a subsequence, It believe it can be done as follows:

def lister(small,big):
    for i in range(len(small)):
        if small[i] not in big:
            return False
    if  " ".join([str(x) for x in small]) in str(" ".join([str(y) for y in big])):
        return True
    else:
        return False


print(lister([3,5],[1,2,3,4,5]))
repzero
  • 8,254
  • 2
  • 18
  • 40
0

Here's a recursive approach. It works for all of your examples. Basically list1 is a subsequence of list2 if A) the first element of list1 is in list2 and B) the remainder of list1 is a subsequence of the remainder of list2.

def subsequence(list1, list2):
     if not list1:
             return True
     head, *tail = list1
     try:
             index = list2.index(head)
             return subsequence(tail, list2[index+1:])
     except ValueError:
             return False
Denziloe
  • 7,473
  • 3
  • 24
  • 34
0

Here is another option:

def IsListInList(listA, listB):
    res = False
    for index,val in enumerate(listA):
        if (val in listB):
            listB = listB[listB.index(val)+1:]
            res = True
        else:
            res = False
            break
    return res
Brian O'Donnell
  • 1,836
  • 19
  • 29