我做了一个计算巧合指数的程序,但似乎是错的。我不知道我的错误在哪里。在
我的计划:
import string
def apparitions(chaine) :
app = [0] * 26
for c in chaine :
if c in string.ascii_uppercase :
app[ord(c) - ord('A')] += 1
return app
def indice_coincidence(chaine) :
app = apparitions(chaine)
s = sum (n*(n-1) for n in app)
somme = sum(app)
return s / (somme*(somme-1))
PP_texte = open('PP.txt', 'r')
P=PP_texte.read()
print(indice_coincidence(P))
我用Little Prince by Antoine de Saint Exupéry尝试了我的程序,用法语(因为我是)和我的程序返回0.08413880573688703
。在
我知道在法语中,指数约为0.074。所以尝试了一个reference website about cryptography,结果是0.07446
总之,我的计划一定是错的。你能告诉我为什么吗?在
省去很多麻烦,使用
collections.Counter
来计算字母出现的频率。在您应该尝试打印您的字母频率数组,并将其与网站上的频率数组进行比较:)
当我用你的代码做这些时,我得到:
这与网站上所说的相去甚远。稍加调试,您将看到您只检查大写字母!在
我的解决方法是将for循环改为:
得到了预期的输出:)
注意:您的代码和网站都不认为重音字母是“字母表”的一部分。例如“é”根本不算在内!在
相关问题 更多 >
编程相关推荐