-2

i have an array in python that looks like this ['u1jr00', 'u1jr01', 'u1jr02', 'u1jr03', 'u1jr04', 'u1jr05', 'u1jr06','u1jrbjk']. i am trying to find the element in this array that closely matches with this string in the query u1jrbjvnrqz7. How can i scan through the whole array and find the elements with the most common prefix matchin with the query string ? are there any built-in functions in python for common prefix matching?

Rehan Aziz
  • 107
  • 2
  • 14

1 Answers1

1

Here's a one-liner:

items = ["abc", "abcd", "abcde", "zasd"]
query = "abcd"
best_match = max((os.path.commonprefix([item, query]), item) for item in items)[1]

This treats all items with the same length of common prefix equally. If you want to prefer smaller ones:

best_match = max((os.path.commonprefix([item, query]), -len(item), item) for item in items)[2]
Joe Halliwell
  • 1,155
  • 6
  • 21