2006年12月13日

Cookbook of Python之学习:Hamming distance


ASPN网站上组织了Python Cookbook,有很多的列举出来的代码片段和相关心得,见http://aspn.activestate.com/ASPN/Cookbook/Python/。其中相关文章分为三类“Editors Pick”、“Approved”、和“Not Approved”。分析了一下,感觉Approved类值得认真学习。今天学习了其中的一篇Hamming distance
全文如下:
------------------------------
Title: Hamming distance
Submitter: Michael Mayhew (other recipes)
Last Updated: 2006/12/11
Version no: 1.0
Category: Text

Description:

Was doing some work with strings and threw this together. This will calculate the Hamming distance (or number of differences) between two strings of the same length.

Source: Text Source

def hamdist(str1, str2):
"""Count the # of differences between equal length strings
str1 and str2"
""
diffs = 0
for ch1, ch2 in zip(str1, str2):
if ch1 != ch2:
diffs += 1
return diffs


print hamdist("iloveir","irlovei")

------------------------------

海明距离的定义是:两个码字的对应比特取值不同的比特数称为这两个码字的海明距离。一个有效编码集中,任意两个码字的海明距离的最小值称为该编码集的海明距离。
用途:海明码的基本意思是给传输的数据增加r个校验位,从而增加两个合法消息(合法码字)的不同位的个数(海明距离)。
代码中zip是第一次见到,python中help(zip)后得到如下指示:

------------------------------
>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
------------------------------

感觉这个函数对于需要逐个字符的比较多个字符串是相当有用的。

呵呵,感觉学习这个资源很有收获,以后会尽量贴出一些学习心得的。Welcome~@!

没有评论:

发表评论