我做了这个代码,但它不是完美的,因为它返回的关键是最高的价值,但不返回一个先来的字母顺序。我如何让它返回字母表中第一个? 而且,我应该按照提示做,但我做的不同。根据提示我该怎么做?你知道吗
Complete the most_frequent() function below so that it returns the most frequently occurring word in a given string.
For example, if the input s is s = 'I scream you scream we all scream for ice cream', the result should be scream as it is the most frequent word in this sentence.
If there is a tie for the most common word, return only one result, the first (tied) word in alphabetical order.
"""Quiz: Most Frequent Word"""
def most_frequent(s):
"""Return the most frequently occuring word in s."""
# HINT: Use the built-in split() function to transform the string s into an
# array
words = s.split(" ")
# HINT: Sort the new array by using the built-in sorted() function or
# .sort() list method
# HINT: Iterate through the array and count each occurance of every word
# using the .count() list method
dict = {}
for word in words:
dict[word] = words.count(word)
# HINT: Find the number of times the most common word appears using max()
result = max(dict, key=dict.get)
# HINT: Locate the index of the most frequently seen word
# HINT: Return the most frequent word. Remember that if there is a tie,
# return the first (tied) word in alphabetical order.
return result
def test_run():
"""Test most_frequent() with some inputs."""
print(most_frequent("cat bat mat mat cat")) # output: 'cat'
print(most_frequent("betty bought a bit of butter but the butter was bitter")) # output: 'butter'
if __name__ == '__main__':
test_run()
在
sorted
中使用键参数。根据频率(值)从高到低排序,然后按键的顺序对元组进行排序如果您想使用集合中的计数器来减少一些代码行
reverse=False
是可选的一点也不酷的解决方案:
相关问题 更多 >
编程相关推荐