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?
Asked
Active
Viewed 57 times
-2

Rehan Aziz
- 107
- 2
- 14
-
1Are you looking for the element that has the longest shared prefix with the query term? – Joe Halliwell Dec 20 '18 at 09:26
-
This is too localized. What does all of this code have to do with the question in the title? – timgeb Dec 20 '18 at 09:27
-
@JoeHalliwell ...@timgeb yes that's exactly what i am looking for. how can i get that? – Rehan Aziz Dec 20 '18 at 09:49
-
@JoeHalliwell..@timgeb could you please take back the downvotes on my question as this question has been answered properly and i have edited the question accordingly? i don't want to have my account blocked – Rehan Aziz Feb 06 '19 at 11:09
-
I think your question is okay; I haven't downvoted it. – Joe Halliwell Feb 10 '19 at 10:16
1 Answers
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