Keep longest substring if condition matches

Viewed 87

Assume, I have the list of strings as follows:

lst = ['practical matter', 'a practical matter', 'As a practical matter',
       'the West', 'the West Coast', 'to Hawaii', 'the West Coast to Hawaii']

I want to keep the longest string if the only difference between them is a starting "a", "the". For example, I want to keep 'a practical matter' as there is an 'a' at the start. Similarly, I want to keep 'the West Coast' as there is a 'the' at the start.

out = ['a practical matter', 'As a practical matter',
       'the West Coast', 'to Hawaii', 'the West Coast to Hawaii']

I tried to do:

delete_from_best_constituents = []
for u in best_parse_constituents:
    for v in best_parse_constituents:
        if u.lower().startswith('the') or v.lower().startswith('the'):
            u_part = u.lower().split('the')[-1].strip()
            v_part =  v.lower().split('the')[-1].strip()
            cond1 = all([w.lower() not in STOP for w in u_part.split()])
            cond2 = all([w.lower() not in STOP for w in v_part.split()])
            if u_part == v.lower() or v_part == u.lower() and cond1 and cond2:
                if not u.lower().startswith('the'):
                    delete_from_best_constituents.append(u)

But I am looking for a concise and a pythonic approach.

1 Answers

I'm not sure how to understand the filter criteria you mentioned, but as you asked for a more pythonic way for your code you might try to write a function that specifies if a string is accepted and use list comprehension with a filter method.

def isValid(e,arr):
    for a in arr:

        #might break if the same string is contained twice in `arr`
        #you could convert `arr` to set()
        if e!=a: 

            #modify to match your criteria
            condition = e in a 
            
            if condition:
                return False;
    return True
[u for u in lst if isValid(u,lst)]

You can shorten this further by adding a second list comprehension

[u for u in lst if not any(
        [ (u != v) and (u in v) for v in lst ]
    ) 
]

The above snippets will return the list ['As a practical matter', 'the West Coast to Hawaii'].

Related