python-3.x - 如何改进此算法以计算字符串中字符的频率?
问题描述
为了以降序方式排序字符串中字符出现的频率,我开发了以下算法。
首先,我将字符串传递给字典,使用每个字符作为键,并将其出现频率作为值。之后,我将字典转换为降序排序的多维列表。
我想知道如何改进算法,这是一个好方法吗?可以做不同的吗?欢迎所有建议。
#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
解决方案
你做的工作太多了。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)
推荐阅读
- android - 无法修复 Fabric 上的崩溃...在 recyclerview 方法中
- r - dplyr 之间的情况
- perl - Perl Mojolicious 模型
- c# - Amazon DynamoDB InvalidOperationException on AWS
- c++ - C++ template with variadic argument specialization for number of arguments
- python - 确定请求的速率限制
- android - CoordinatorLayout 中 RecyclerView 的滚动问题
- sql - 使用 SQL 在 Oracle 中获取重复的元组
- c# - 在异步任务期间关闭表单时转换方法中的异常
- android - 加载广告而不显示它可以吗?