Issue
Having this array with code
and collection
, where X
is a mask that can be "any number":
input_array = [{"code": "XXXX10", "collection": "one"}, {"code": "XXX610", "collection": "two"}, {"code": "XXXX20", "collection": "three"}]
I want a function that given any 6 digit code, for example 000710
returns the value that matches the best code mask (for the example would be one
). This is my try:
def get_collection_from_code(analysis_code):
for collection in input_array:
actual_code = collection["code"]
mask_to_re = actual_code.replace("X", "[\d\D]")
pattern = re.compile("^" + mask_to_re + "$")
if pattern.match(analysis_code):
print("Found collection '" + str(collection["collection"]) + "' for code: " + str(analysis_code))
return collection["collection"]
res = get_collection_from_code("010610")
print(res)
The problem here is that if I inpuit the code 010610
(and I want to return two
), it returns one
as also matches the pattern XXXX10
first.
For better understanding, if I input there values, I would like to have those ouputs:
010610 > two
010010 > one
123420 > three
Solution
You could iterate the entire collection, saving the length of the "X" part of any match, and then return the shortest:
input_array = [{"code": "XXXX10", "collection": "one"}, {"code": "XXX610", "collection": "two"}, {"code": "XXXX20", "collection": "three"}]
def get_collection_from_code(analysis_code):
results = {}
for collection in input:
actual_code = collection["code"]
mask_to_re = actual_code.replace("X", "[\d\D]")
pattern = re.compile("^" + mask_to_re + "$")
if pattern.match(analysis_code):
results[collection["collection"]] = actual_code.count('X')
if len(results):
best = sorted(results.items(), key=lambda i:i[1])[0]
print("Found collection '" + str(best[0]) + "' for code: " + str(analysis_code))
return best[0]
res = get_collection_from_code("010610")
# Found collection 'two' for code: 010610
Note I've saved all the matches in case you want to process them in any way. Otherwise you could just check for the "best" match in each iteration and update that instead.
Answered By - Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.