微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

任何用于最佳最精确字符串匹配如路由表的内置 Python 库或函数?如果不是,我的代码是最有效的吗?

如何解决任何用于最佳最精确字符串匹配如路由表的内置 Python 库或函数?如果不是,我的代码是最有效的吗?

代码示例:

# Something
dept_dict = {
    # Generally,employee code starting with '15' means Department A,'16' B,'17' C.
    '15': 'Department A','16': 'Department B','17': 'Department C',# Exception: sub dept '15.233' and '17.312' belonged to dept A and C but Now B.
    '15.233': 'Department B','17.312': 'Department B',# Exception: employees who had transferred to another department.
    '15.233.19305': 'Department C','15.330.19306': 'Department B',}
# Requirement: use exception (exact matched) item if it exists,otherwise "fall" to general item.


# Is there any built-in function implement the following?
def get_dept(emp_code):
    dept_name = None
    for i in range(len(emp_code),-1,-1):
        dept_name = dept_dict.get(emp_code[0:i])
        if dept_name:
            break
    return dept_name


# Test code:
print(get_dept('15.233.19305'))  # The employee who transferred to Dept C from Dept A
print(get_dept('15.233.19300'))  # The employee who belongs to a sub dept,all employees of which have transferred to Dept B from Dept A
print(get_dept('15.147.13500'))  # The employee who belongs to Dept A just like most of the employees
print(get_dept(''))

结果:

Department C
Department B
Department A
None

对于函数“get_dept”,是否有已经实现的内置函数?我重新发明了轮子吗?

在这个网站上读过一些贴有“最精确匹配”的帖子,但其中大部分都是关于“模糊搜索”的,例如将“部门”与[“部门”,“部门”]匹配,这是不是我想要的。当我搜索“路由表”时,我得到了“URL匹配”之类的帖子,这也不是我想要的。

似乎是“路由表”使用的底层技术。

如果没有这样的内置函数,问题将是:我的实现是最有效的吗?我应该使用,例如二分搜索还是其他什么?


(已编辑)

感谢发表评论的人(但不知何故删除了它)。评论说构建 Trie 可能是一种选择。如果 dict 不经常更改并且有很多查询,则可以忽略构建 Trie 的开销。

解决方法

这将最坏的情况从 11 次字典查找减少到 3 次。假设没有灵丹妙药,您可能会考虑这些方面的事情。

示例:

def get_dept(emp_code):
    
    emp_sub_codes = emp_code.split(".")

    while emp_sub_codes:
        dept_name = dept_dict.get(".".join(emp_sub_codes))
        if dept_name:
            return dept_name
        emp_sub_codes = emp_sub_codes[:-1]

    return None

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。