-1
def sublist(slist, blist):
    m = 0
    is_a_sublist = False
    for n in range(0, len(blist)):
     while (n < len(blist) and m < len(blist)) and is_a_sublist == False:
            spliced_list = blist[n:m]
            if spliced_list == slist:
                is_a_sublist = True
            else:
                m += 1

    return is_a_sublist

def main():
    test_list = ["a",9,1,3.14,2]
    original_list = ["a",1,"a",9,1,3.14,2]

    is_a_sublist = sublist(test_list,original_list)

    if is_a_sublist == True:
        print("It is a sublist!")
    else:
        print("It ain't a sublist!")


main()

The code I wrote above is to check if a given list is a "sublist" of a larger list. So, if a large list is [3,3,10,4,9], and the given list is [3,10,4], then it is a sublist so it must return True. But what's wrong with my code? When I run it, output is "It ain't a sublist" even though it is (function returns False). I only want to use loops, no built-in functions.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
janissary
  • 103
  • 3

2 Answers2

0

you can use:

def sublist(l2, l1):
    for i in range(0, len(l2) - len(l1) + 1):
        if l2[i] == l1[0]:
            for j in range(1, len(l1)):
                if l2[i + j] != l1[j]:
                    break
            else:
                return True
    return False


l1 = [3,3,10,4,9]
l2 = [3,10,4]

sublist(l1, l2)
# True
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

It's erroroneous for your code to have a for loop followed by a while loop. Only for loop is needed to loop over blist.

So this is code is in error:

for n in range(0, len(blist)):
     while (n < len(blist) and m < len(blist)) and is_a_sublist == False:

Simplified Code

By simplyfying looping, removing superfluous variables and steps, your code can be simplified to the following:

def sublist(slist, blist):
  for n in range(len(blist)-len(slist)+1):
    if slist == blist[n:n+len(slist)]:
      return True
  return False

def main():
    test_list = ["a",9,1,3.14,2]
    original_list = ["a",1,"a",9,1,3.14,2]

    if sublist(test_list,original_list):
        print("It is a sublist!")
    else:
        print("It ain't a sublist!")

main()

Output

It is a sublist!

Explanation

Code:

for n in range(len(blist)-len(slist)+1):
# We're looking for a starting index between
# 0 and len(blist)-len(slist)
# The reason it can be at most 
# len(blist)-len(list) 
# is that's the max index that still could 
# have len(slist) elements
# range(len(blist)-len(slist)+1) provides
# numbers from 0 to en(blist)-len(slist)
   if slist == blist[n:n+len(slist)]:
 # Check if we have a match from n to
 # n + len(slist) - 1 (i.e. since slice
 # a:b means index of elements from a to b-1
DarrylG
  • 16,732
  • 2
  • 17
  • 23