【问题标题】:How to return the number of characters whose frequency is above a threshold如何返回频率高于阈值的字符数
【发布时间】:2012-03-27 18:01:17
【问题描述】:

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

作业题是:

您的任务是编写一个函数,该函数将单个非负数作为输入并返回(不打印)计数中严格大于函数参数的字符数。你的函数应该被称为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]

不行,就是不知道哪里错了。

【问题讨论】:

  • 在什么意义上它不起作用?它会引发异常吗?它会打印错误的结果吗?
  • 比较你的作业中的返回规范(“返回字符数”)和你的返回语句。
  • 为什么每次按键的频率低于阈值时都返回threshold?如果阈值为 5,并且没有频率 >= 5 的大写字符,则您的函数将返回 5,而它应该返回 0。基本上,计数看起来不错,但您需要考虑应该返回什么结果.

标签: python statistics


【解决方案1】:

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

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

您可以使这段代码更符合 Python 风格。我这样写是为了更清楚。

【讨论】:

    【解决方案2】:

    计算每个字符数量的部分很好:

    >>> 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 或一个 特定 字符出现的次数。

    您需要逐步计算字符数和字符数,并计算有多少字符的频率超过 n。 p>

    【讨论】:

      【解决方案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})
      

      【讨论】:

        【解决方案4】:
        from collections import Counter
        def freq_threshold(s, n):
            cnt = Counter(s)
            return [i for i in cnt if cnt[i]>n and i.isupper()]
        

        重新发明轮子:

        def freq_threshold(s, n):
            d = {}
            for i in s:
                d[i] = d.get(i, 0)+1
            return [i for i in d if d[i]>n and i.isupper()]
        

        【讨论】:

        • 不完全是任务要求的 - 你想要那个返回列表的len()。
        猜你喜欢
        • 1970-01-01
        • 2013-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 2015-07-01
        • 1970-01-01
        相关资源
        最近更新 更多