My current implementation is this:
def find_longest_matching_option(option, options):
options = sorted(options, key=len)
longest_matching_option = None
for valid_option in options:
# Don't want to treat "oreo" as matching "o",
# match only if it's "o reo"
if re.match(ur"^{}\s+".format(valid_option), option.strip()):
longest_matching_option = valid_option
return longest_matching_option
Some examples of what I'm trying to do:
"foo bar baz something", ["foo", "foo bar", "foo bar baz"]
# -> "foo bar baz"
"foo bar bazsomething", (same as above)
# -> "foo bar"
"hello world", ["hello", "something_else"]
# -> "hello"
"a b", ["a", "a b"]
# -> "a b" # Doesn't work in current impl.
Mostly, I'm looking for efficiency here. The current implementation works, but I've been told it's O(m^2 * n)
, which is pretty bad.
Thanks in advance!