aiaiask.com©

开花即结果 提问即答案

请统计给定字符串中长度≥k的单词出现次数,并输出频率最高的单词(若多解则优先按长度较短、其次按字典序较小排序),若无解则输出-1。
原始问题:

请统计给定字符串中长度≥k的单词出现次数,并输出频率最高的单词(若多解则优先按长度较短、其次按字典序较小排序),若无解则输出-1。

以下是一个解决该问题的Python代码示例:

from collections import Counter

def find_most_frequent_word(k, string):
    words = string.split()
    word_counts = Counter(words)
    filtered_words = [word for word in word_counts if len(word) >= k]
    
    if not filtered_words:
        return -1
    
    max_count = max(word_counts[word] for word in filtered_words)
    most_frequent_words = [word for word in filtered_words if word_counts[word] == max_count]
    
    return min(most_frequent_words, key=lambda x: (len(x), x))

k = int(input())
string = input()

result = find_most_frequent_word(k, string)
print(result)

该代码首先将输入的字符串按空格分割成单词,并使用Counter类统计每个单词的出现次数。然后,筛选出长度大于等于k的单词,并找出其中出现次数最多的单词。如果没有满足条件的单词,则返回-1。最后,根据题目要求,选择长度较小且字典序较小的单词作为结果输出。

请注意,以上代码仅为示例,可能需要根据实际情况进行调整。

请统计给定字符串中长度≥k的单词出现次数,并输出频率最高的单词(若多解则优先按长度较短、其次按字典序较小排序),若无解则输出-1。
https://www.aiaiask.com/ask/45744.html
AI / 模型Siliconflow
时间 / DATESeptember 2, 2023, 4:54 PM
语言zh-CN
IP / 区域香港