Skip to content Skip to sidebar Skip to footer

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 t

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

Solution 2:

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

Post a Comment for "Correct Output For Function That Counts Occurrences Of Each Digit In A String"