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:
defcount_digits(s):
res = [0]*10for x in s:
res[int(x)] += 1return res
defprint_counts(counts):
for (index, count) inenumerate(counts):
if count == 1:
print("%d occurs %d time" % (index, count))
elif count > 1:
print("%d occurs %d times" % (index, count))
defmain():
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 notin d:
d[i] = 1else:
d[i] += 1for 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"