python列表包含子列表_python列表和子列表

I have to check if list1 is contained in list2. It also should check if it appears in that order in the list as well. If it's true, it should return true and false if it doesn't.

def check(lst1, lst2):

for x in lst1:

for y in lst2:

xx = lst1.sort()

yy = lst2

if xx != yy:

return False

else:

return True

I'm confusing myself with the for loops and also, I don't know where to go from here to fix my code. Pointers please?

example of what it should do:

check([4,0],[9,1,4,6,8,9])

True

check([1,2],[2,3,1])

False

解决方案

I thought the problem was begging to be solved recursively, so I did:

def check(needle, haystack):

if not needle:

return True

try:

offset = haystack.index(needle[0])

return check(needle[1:], haystack[offset+1:])

except:

return False

Edit:

Brief explanation:

First we check if the list we're looking for is empty (this is important once we start calling ourselves), since all lists have the empty list inside it, we return True. Then we try finding the first item of the list we're looking for in the list we're looking at. If we find it, we then call the function again, but change the arguments a bit: we already looked at the first item of the 'needle' and saw it in the 'haystack'. So now we need to check if the remainder of 'needle' is in the remainder of 'haystack'. So we call the function again only with the remainder of both lists. The remainder of needle is everything but the first element, and the remainder of haystack is all items after the one we found. If we get to a point where the first list is empty, it means we found it in the haystack. If we get an exception, what we were looking for wasn't found, so we return False, which bubbles up the call stack and gets returned.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值