首页 > 解决方案 > 如何改进此算法以计算字符串中字符的频率?

问题描述

为了以降序方式排序字符串中字符出现的频率,我开发了以下算法。

首先,我将字符串传递给字典,使用每个字符作为键,并将其出现频率作为值。之后,我将字典转换为降序排序的多维列表。

我想知道如何改进算法,这是一个好方法吗?可以做不同的吗?欢迎所有建议。

#Libraries
from operator import itemgetter
# START

# Function
# String to Dict. Value as freq. 
# of appearance and char as key.
def frequencyChar(string):
    #string = string.lower() # Optional
    freq = 0
    thisDict = {}
    for char in string:
        if char.isalpha(): # just chars
            freq = string.count(char)
            thisDict[char] = freq # {key:value}
    return(thisDict)

str2Dict = frequencyChar("Would you like to travel with me?")
#print(str2Dict)
# Dictionary to list
list_key_value = [[k,v] for k, v in str2Dict.items()]
# Descending sorted list
list_key_value = sorted(list_key_value, key=itemgetter(1), reverse=True)

print("\n", list_key_value, "\n")

#END

标签: python-3.xdictionarymultidimensional-array

解决方案


你做的工作太多了。collections.Counter自动为您计数,甚至按频率排序:

from collections import Counter
s = "Would you like to travel with me?"
freq = Counter(s)
# Counter({' ': 6, 'o': 3, 'l': 3, 'e': 3, 't': 3, 'u': 2, 'i': 2, 'W': 1, 'd': 1, 'y': 1, 'k': 1, 'r': 1, 'a': 1, 'v': 1, 'w': 1, 'h': 1, 'm': 1, '?': 1})

如果要从计数中删除空格:

del freq[' ']
# Counter({'o': 3, 'l': 3, 'e': 3, 't': 3, 'u': 2, 'i': 2, 'W': 1, 'd': 1, 'y': 1, 'k': 1, 'r': 1, 'a': 1, 'v': 1, 'w': 1, 'h': 1, 'm': 1, '?': 1})

同样,一般来说,您的算法做的工作太多。string.count涉及为您要计数的每个字符迭代整个字符串。相反,您可以在整个字符串上迭代一次,并且对于每个字母,您只需不断增加与该字母关联的键(如果它是您以前从未见过的字母,则将其初始化为 1)。这基本上就是Counter为你做的事情。

拼写出来:

count = {}
for letter in the_string:
    if not letter.isalpha():
        continue
    if letter not in count:
        count[letter] = 1
    else:
        count[letter] += 1

然后对其进行排序,您不需要先转换为列表,您可以直接进行:

ordered = sorted(count.items(), key=itemgetter(1), reverse=True)

推荐阅读