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

后端 未结 3 634
自闭症患者
自闭症患者 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 07:12

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

提交回复
热议问题