Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 10 - Lists - Programming Exercises - Page 356: 10.31

Answer

code

Work Step by Step

# 10.31 (Occurrences of each digit in a string) Write a function that counts the occurrences # of each digit in a string using the following header: # def count(s): # The function counts how many times a digit appears in the string. The return # value is a list of ten elements, each of which holds the count for a digit. For # example, after executing counts = count("12203AB3"), counts[0] is 1, # counts[1] is 1, counts[2] is 2, and counts[3] is 2. # Write a test program that prompts the user to enter a string and displays the # number of occurrences of each digit in the string. def getDistinctDigits(s): lst = [] for x in s: if x not in lst: lst.append(x) return lst def count(s): counts = [] lst = getDistinctDigits(s) for i in range(len(lst)): n = lst[i] counts.append(s.count(n)) return counts s = input("Enter a string: ") counts = count(s) s = list(s) lst = getDistinctDigits(s) lst2 = [x for x in lst] lst.sort() for i in lst: print(i, "occurs", counts[lst2.index(i)], "times")
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.