Python: Determine whether list of lists contains a defined sequence

Posted by duhaime on Stack Overflow See other posts from Stack Overflow or by duhaime
Published on 2014-08-23T03:10:21Z Indexed on 2014/08/23 4:20 UTC
Read the original article Hit count: 95

Filed under:
|
|
|

I have a list of sublists, and I want to see if any of the integer values from the first sublist plus one are contained in the second sublist. For all such values, I want to see if that value plus one is contained in the third sublist, and so on, proceeding in this fashion across all sublists. If there is a way of proceeding in this fashion from the first sublist to the last sublist, I wish to return True; otherwise I wish to return False. In other words, for each value in sublist one, for each "step" in a "walk" across all sublists read left to right, if that value + n (where n = number of steps taken) is contained in the current sublist, the function should return True; otherwise it should return False. (Sorry for the clumsy phrasing--I'm not sure how to clean up my language without using many more words.)

Here's what I wrote.

a = [ [1,3],[2,4],[3,5],[6],[7] ]

def find_list_traversing_walk(l):

    for i in l[0]:

        index_position = 0
        first_pass = 1
        walking_current_path = 1

        while walking_current_path == 1:

            if first_pass == 1:
                first_pass = 0
                walking_value = i

            if walking_value+1 in l[index_position + 1]:

                index_position += 1
                walking_value  += 1

                if index_position+1 == len(l):
                    print "There is a walk across the sublists for initial value ", walking_value - index_position
                    return True

            else:
                walking_current_path = 0

    return False

print find_list_traversing_walk(a)

My question is: Have I overlooked something simple here, or will this function return True for all true positives and False for all true negatives? Are there easier ways to accomplish the intended task? I would be grateful for any feedback others can offer!

© Stack Overflow or respective owner

Related posts about python

Related posts about algorithm