Python 动态规划算法,计算单词距离

这个脚本python 2.4不可执行但在python26中可以

可以作为一个python语法进化的参考

 

centos中python默认是python2.4.3

安装完rpmforege或是epel后使用

yum install python26之后可以调用

python26来执行脚本

另外搜索 yum search python27是没有的

Python 动态规划算法,计算单词距离 - 代码分享 - 开源中国社区

 

[代码] [Python]代码

01#!/usr/bin/env python
02#coding=utf-8
03 
04def word_distance(m,n):
05    """compute the least steps number to convert m to n by insert , delete , replace .
06    动态规划算法,计算单词距离
07    >>> print word_distance("abc","abec")
08    1
09    >>> print word_distance("ababec","abc")
10    3
11    """
12    len_1=lambda x:len(x)+1
13    
14    c=[[i] for i in range(0,len_1(m)) ]
15    c[0]=[j for j in range(0,len_1(n))]
16    
17    for i in range(0,len(m)):
18    #    print i,' ',
19        for j in range(0,len(n)):
20            c[i+1].append(
21                min(
22                    c[i][j+1]+1,#插入n[j]
23                    c[i+1][j]+1,#删除m[j]
24                    c[i][j] + (0 if m[i]==n[j] else 1 )#改
25                )
26            )
27    #        print c[i+1][j+1],m[i],n[j],' ',
28    #    print ''
29    return c[-1][-1]
30 
31import doctest
32doctest.testmod()
33raw_input("Success!")
posted on 2012-10-10 14:29  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2012/10/10/2718276.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值