问答系统中的递归和动态规划

递归——分词

def full_segmentation(input_str, words): # 输入字符串 字典
    if input_str == '':
        return [[]]
    
    else:
        result = []
        for i in range(1, len(input_str) + 1):
            if input_str[:i] in words:
                for remain_segment in full_segmentation(input_str[i:], words):
                    result.append([input_str[:i]] + remain_segment)    
        return result
words = ['我们','学习','人工','智能','人工智能','未来','是']
input_str = '我们学习人工智能人工智能是未来'
result = full_segmentation(input_str, words)
print(result)

输出

输出

上面可以优化————>动态规划

def get_graph(input_str):
    graph = collections.Orderedict()
    for i in range(len(input_str) + 1):
        for i not in graph:
            graph[i] = {}
        for j in range(i):
            if input_str[j:i] in word_score.keys():
                graph[i][j] = word_score[input_str[j:i]]
    return graph

#0     1     2   3 ....
#   字   字   字
def get_best_path(path):
    score = {0 : 0}
    path = {}
    for i in graph.keys():   # 以字典来表示图
        if graph[i]:
            for j in graph[i].keys():
                if i not in score.keys() or score[i] > graph[i][j] + score[j]:
                    score[i] = graph[i][j] + score[j]
                    path[i] = j
    return path
            
#0     1    2    3 ....
#   字   字   字
def path_to_segment(path, input_str):
    segment = []
    i = max(path.keys())
    while i >0 :
        segment = [input_str[path[i]:i]] + segment
        i = path[i]
        
    return segment
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值