相关疑难解决方法(0)

Python - 字典是否很难找到每个字符的频率?

我试图使用O(n)复杂度的算法在任何给定文本中找到每个符号的频率.我的算法看起来像:

s = len(text) 
P = 1.0/s 
freqs = {} 
for char in text: 
    try: 
       freqs[char]+=P 
    except: 
       freqs[char]=P 
Run Code Online (Sandbox Code Playgroud)

但我怀疑这个字典方法足够快,因为它取决于字典方法的底层实现.这是最快的方法吗?

更新:如果使用集合和整数,速度不会增加.这是因为该算法已经具有O(n)复杂度,因此不可能实现必要的加速.

例如,1MB文本的结果:

without collections:
real    0m0.695s

with collections:
real    0m0.625s
Run Code Online (Sandbox Code Playgroud)

python algorithm probability frequency

24
推荐指数
5
解决办法
5131
查看次数

标签 统计

algorithm ×1

frequency ×1

probability ×1

python ×1