简体   繁体   中英

Checking if a list contains a sublist

I'm working on the following practice problem from codingbat:

Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.

I've written:

def array123(nums):
    array = [1,2,3]
    for i in nums:
        sub = nums[i:i+3] 
        if array == sub:
            return True
     return False

It keeps failing when the string is [1,2,3], any other combination of numbers works. I understand the solution codingbat gives, but I don't understand why my code is only failing in that instance. What am I doing wrong?

for i in nums: successively assigns to i the value of the items of list nums .

However you appear to believe it's assigning indices rather than value -- perhaps that's because it's what it the equivalent construct would to in Javascript.

So make i iterate over the indices -- for i in range(len(nums)-3): and the rest of your code seems fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM