Skip to content Skip to sidebar Skip to footer

Find Generic Sub-lists Within A List

Just learning Python as my first coding language. Given a list with many possible sub-lists which have a variable number of elements, is there a way of using regex (or something si

Solution 1:

I agree that converting to string doesn't make any sense here, but regular expressions explicitly search strings so you're not looking for that either. You're looking for a recursive solution that tests for your rules, which are (essentially)

somelist IS or CONTAINS a list that begins with the string "a", ends with the string "b", and has three or more elements.

Codify that into:

defflat_pass(lst):
    returnlen(lst) >= 3and lst[0] == 'a'and lst[-1] == 'b'

Now you just have to recurse (to catch the "CONTAINS" part of the above rules)

defrecurse_pass(lst):
    iflen(lst) >= 3and lst[0] == 'a'and lst[-1] == 'b':
        # base casereturnTrue# otherwise, flow continues...for el in lst:
        ifisinstance(el, list):
            # recursive caseif recurse_pass(el):
                returnTruereturnFalse

Post a Comment for "Find Generic Sub-lists Within A List"