如何返回频率高于阈值的字符数

2024-06-28 19:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何打印频率高于阈值的大写字符数(在教程中)?在

作业问题是:

Your task is to write a function which takes as input a single non-negative number and returns (not print) the number of characters in the tally whose count is strictly greater than the argument of the function. Your function should be called freq_threshold.

我的回答是:

mobyDick = "Blah blah A B C A RE."

def freq_threshold(threshold):
    tally = {}
    for char in mobyDick:
        if char in tally:
            tally[char] += 1
        else:
            tally[char] = 1

    for key in tally.keys():
        if key.isupper():
            print tally[key],tally.keys
            if threshold>tally[key]:return threshold
            else:return tally[key]

这不管用,但我不知道哪里错了。在


Tags: ofthekeyinnumberyourthresholdif
3条回答

不要重新发明轮子,而是使用counter object,例如:

>>> from collections import Counter
>>> mobyDick = "Blah blah A B C A RE."
>>> c = Counter(mobyDick)
>>> c
Counter({' ': 6, 'a': 2, 'B': 2, 'h': 2, 'l': 2, 'A': 2, 'C': 1, 'E': 1, '.': 1, 'b': 1, 'R': 1})

你把每个字符的数字加起来的部分很好:

>>> pprint.pprint ( tally )
{' ': 5,
 '.': 1,
 'A': 2,
 'B': 2,
 'C': 1,
 'E': 1,
 'R': 1,
 'a': 2,
 'b': 1,
 'h': 2,
 'l': 2,
 '\x80': 2,
 '\xe3': 1}

错误在于你是如何总结计票结果的。在

  • 您的作业要求您打印字符串中出现次数超过n次的字符数。在
  • 您返回的是n或一个特定字符发生的次数。在

相反,您需要逐步检查字符计数和字符计数,count有多少字符的频率超过n。在

您的任务是返回满足条件的字符数。您试图返回某个字符的出现次数。试试这个:

result = 0
for key in tally.keys():
  if key.isupper() and tally[key] > threshold:
    result += 1
return result 

你可以让这段代码更像Python。我这样写是为了让它更清楚。在

相关问题 更多 >