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

与世无争的帅哥 提交于 2019-11-27 08:47:51

问题


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

This is the program that I have so far. At it's current state, if a user enters something like 122033 the output is: [1,1,2,2]

Note: I cannot use collections for this.


回答1:


You're pretty close to a working solution, but removing all the 0-count entries changes the indices of your list. You already need to write some custom pretty printing code, so just leave the 0s in and skip elements where the count is 0. Maybe something like this:

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:


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.




回答3:


An approach that does not use counters:

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


来源:https://stackoverflow.com/questions/19694533/correct-output-for-function-that-counts-occurrences-of-each-digit-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!