为什么我在python3.4中对巧合索引程序有错误

2024-09-28 03:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个计算巧合指数的程序,但似乎是错的。我不知道我的错误在哪里。在


我的计划:

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


总之,我的计划一定是错的。你能告诉我为什么吗?在


Tags: in程序appforstringreturndef指数
2条回答

省去很多麻烦,使用collections.Counter来计算字母出现的频率。在

In [1]: import collections

In [2]: collections.Counter('This is a test with accented characters à é ó ú ü')
Out[2]: Counter({' ': 11, 't': 5, 'e': 4, 's': 4, 'c': 4, 'a': 4, 'i': 3, 'h': 3, 'r': 2, 'd': 1, 'ó': 1, 'ú': 1, 'T': 1, 'w': 1, 'é': 1, 'ü': 1, 'à': 1, 'n': 1})

您应该尝试打印您的字母频率数组,并将其与网站上的频率数组进行比较:)

当我用你的代码做这些时,我得到:

Python Output

这与网站上所说的相去甚远。稍加调试,您将看到您只检查大写字母!在

我的解决方法是将for循环改为:

for c in chaine.upper() :
    if c in string.ascii_uppercase :
        app[ord(c) - ord('A')] += 1

得到了预期的输出:)

注意:您的代码和网站都不认为重音字母是“字母表”的一部分。例如“é”根本不算在内!在

相关问题 更多 >

    热门问题