【问题标题】:Find maximum & minimum, and average # of words per line查找最大值和最小值,以及每行的平均单词数
【发布时间】:2021-09-29 23:28:36
【问题描述】:

我在完成一个程序时遇到了一些麻烦。我尝试了许多不同的方法来产生所需的结果:

  1. 创建一个名为 lexicographics() 的函数,它接受一个参数:
    • to_analyze,必填字符串
  2. 使用单个 for 循环,为您的文本计算以下内容:
    • to_analyze 中每行的最大字数(例如,to_analyze 中最长行的长度)
    • to_analyze 中每行的最小字数(例如,to_analyze 中最短行的长度)
    • to_analyze 中每行的平均字数,以小数形式存储。
  3. 按照上面定义的顺序将这些值作为元组返回。

期望的结果应该是:

 >>> lexicographics('''Don't stop believing, Hold on to that feeling.''') 
(5, 3, Decimal(4.0))

但是,我似乎无法准确存储最小字数。我的代码如下:

def lexicographics(to_analyze):
    lines=0
    wordCount=0
    maxWords = 0
    minWords = 0
   
    l = to_analyze.split("\n")

    for line in l:
        lines += 1
        print("line number: ",str(lines), "line text: ",str(line))
        words = line.split()
        print("Words: ", words)
        wordCount = wordCount + len(words)
        if len(words) > maxWords:
            maxWords = len(words)
        elif wordCount > 0 and wordCount < maxWords:
            minWords = wordCount
        print('Word count: {}'.format(len(words)))
    print(maxWords, minWords, "Decimal: {}".format(wordCount / lines), )
     
   
   
lexicographics('''Don't stop believing,
Hold on to that feeling.''')

当我测试程序时,我得到了所需的最大值和平均值,但似乎无法得到正确的最小值。有什么建议吗?

【问题讨论】:

  • 最少字数有什么价值?
  • minWords 的初始值为零,这可能比大多数情况都要小,而且,在您的情况下,您永远不会将您的计数与minWords 进行比较。
  • @duffymo 我得到的最小值为 0
  • @BenY 这不是:elif wordCount &gt; 0 and wordCount &lt; maxWords:minWords = wordCount wordCount 与 minWords 的比较吗?我不确定为什么在遍历行并生成 3 和 5 的 wordCount 后字数会等于 0。

标签: python


【解决方案1】:

我建议最初将minWords 设置为一个标记值,然后将它们进行比较:

    minWords = None
...

   if minWords is None or minWords > len(words):
       minWords = len(words)
...

【讨论】:

  • 谢谢,这会生成正确的最小单词值。
猜你喜欢
  • 2014-06-11
  • 1970-01-01
  • 2021-01-15
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2017-07-24
  • 1970-01-01
相关资源
最近更新 更多