-2

I have a list, say [1, 5, 2, 6, 2, 5, 1].
The items in this list are in the same order in this list: [4, 1, 5, 2, 6, 2, 5, 1, 6, 2, 3]

What's an easy way finding out if a 1-nested lists' items are in the same order in another 1-nested lists' items?

beary605
  • 802
  • 2
  • 9
  • 18

3 Answers3

4

After looking at the question I wrote this. Unlike some of the others that assume that the elements in the first array must occur in the second contiguously, this does not.

def in_order(a,b):
    j = iter(b)
    for i in a:
        while True:
            try:
                j_ = j.next()
            except StopIteration:
                return False
            if i == j_:
                break
    return True

The OP's example:

a = [1, 5, 2, 6, 2, 5, 1]
b = [4, 1, 5, 2, 6, 2, 5, 1, 6, 2, 3]
print in_order(a,b)

prints: True

Dan D.
  • 73,243
  • 15
  • 104
  • 123
0
size = len(needle)
any(needle == haystack[i:i+size] for i in range(len(haystack) - size + 1))
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
-1

Just modify the top answer from here: Testing if a list contains another list with Python

Community
  • 1
  • 1
jgritty
  • 11,660
  • 3
  • 38
  • 60
  • 2
    I am adding +1 for simple fact that when downvoting people should provide a comment that should be helpful to the user – pyfunc Jun 25 '12 at 15:58
  • 1
    @pyfunc I downvoted for copy/paste from duplicate answer already posted – NominSim Jun 25 '12 at 16:00
  • 2
    If this answer solves the question (which isn't clear until the OP clarifies it), then the question should be marked as a duplicate of the other one rather than copy/pasting the answer from there. – interjay Jun 25 '12 at 16:01
  • @NominSim: Sorry. But we should provide the comment. Thanks for coming back. Yeah, we do not want repeated answers in SO. We should just point out in that case – pyfunc Jun 25 '12 at 16:02
  • I have flagged the question as a duplicate... – jgritty Jun 25 '12 at 16:04
  • @pyfunc I actually wasn't sure of the etiquette of copy/pasting an answer from a duplicate question so went to meta to check before coming back to explain the DV. – NominSim Jun 25 '12 at 16:06