Correct output for function that counts occurrences of each digit in a string

后端 未结 3 632
自闭症患者
自闭症患者 2020-12-12 06:16

I want the output of the code to be something like this if the user enters a string of numbers like let\'s say... 122033

Enter string of numbers: 122033
0 oc         


        
3条回答
  •  鱼传尺愫
    2020-12-12 06:59

    Without collections.Counter, here is a pretty short and efficient solution:

    >>> 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
    >>>
    

    As Peter DeGlopper notes in the comment below, this solution will work for any character set, not just digits. If however you want it to only work with digits, all you need to do is make a slight modification to the for-loop line:

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

    Adding if c.isdigit() to the end of that will make it only capture digits.

提交回复
热议问题