Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...