【问题标题】:Correct output for function that counts occurrences of each digit in a string计算字符串中每个数字出现次数的函数的正确输出
【发布时间】:2013-11-10 18:02:06
【问题描述】:

如果用户输入一串数字,比如让我们说... 122033,我希望代码的输出是这样的

Enter string of numbers: 122033
0 occurs 1 time
1 occurs 1 time
2 occurs 2 times
3 occurs 2 times


def count_digits(s):
    res = [0]*10
    for x in s:
        res[int(x)] += 1
    while 0 in res:
        res.remove(0)
    return res

def main():
    s=input("Enter string of numbers: ")

    print(count_digits(s))
main()

这是我到目前为止的程序。在当前状态下,如果用户输入类似 122033 的内容,则输出为: [1,1,2,2]

注意:我不能为此使用集合。

【问题讨论】:

    标签: python counting


    【解决方案1】:

    您非常接近一个可行的解决方案,但删除所有 0 计数条目会更改列表的索引。您已经需要编写一些自定义的漂亮打印代码,所以只需保留 0 并跳过计数为 0 的元素。可能是这样的:

    def count_digits(s):
        res = [0]*10
        for x in s:
            res[int(x)] += 1
        return res
    
    def print_counts(counts):
        for (index, count) in enumerate(counts):
            if count == 1:
                print("%d occurs %d time" % (index, count))
            elif count > 1:
                print("%d occurs %d times" % (index, count))
    
    def main():
        s=input("Enter string of numbers: ")
    
        print_counts(count_digits(s))
    

    【讨论】:

      【解决方案2】:

      如果没有collections.Counter,这是一个非常简短有效的解决方案:

      >>> def count_digits(inp):
      ...     for a,b in sorted((c, inp.count(c)) for c in set(inp)):
      ...         print("{} occurs {} times".format(a, b))
      ...
      >>> mystr = input("Enter string of numbers: ")
      Enter string of numbers: 122033
      >>> count_digits(mystr)
      0 occurs 1 times
      1 occurs 1 times
      2 occurs 2 times
      3 occurs 2 times
      >>>
      

      正如 Peter DeGlopper 在下面的评论中指出的那样,此解决方案适用于任何字符集,而不仅仅是数字。但是,如果您希望它仅适用于数字,您需要做的就是对 for-loop 行稍作修改:

      for a,b in sorted((c, inp.count(c)) for c in set(inp) if c.isdigit()):
      

      在末尾添加if c.isdigit() 将使其仅捕获数字。

      【讨论】:

      • 计数器很棒,但 OP 明确表示“我不能为此使用集合。”
      • 是的,我刚刚看到了。固定。
      • 这具有适用于任何字母的优势,而不仅仅是数字。
      • 此外,如果输入字符串很长,它会快得多。我很惊讶这么多。在我的桌面上重复 1000 次超过一百万个元素的输入字符串需要 107 秒,而基于列表的实现需要 1412 秒。通过自定义实现,内置方法甚至胜过一次遍历。
      【解决方案3】:

      一种不使用计数器的方法:

      d = {}
      
      for i in somestring:
         if i not in d:
           d[i] = 1
         else:
           d[i] += 1
      for k,v in d.iteritems():
         print('{0} occurs {1} times'.format(k,v))
      

      【讨论】:

      • 更简洁的表达方式是d[i] = d.get(i, 0) + 1
      猜你喜欢
      • 2022-10-15
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2013-12-25
      • 2014-04-24
      相关资源
      最近更新 更多