108k views
2 votes
In this problem, you will fill in the code for a function count_digits(val) that takes a positive integer, val, and returns a list containing the count of the number of times that each digit 0 - 9 appears in val. Type the provided code into IDLE (or whatever Python IDE you are using). You will fill in the code where specified in the count_digits function. The function contains the line of code count_lst

1 Answer

1 vote

Answer:

def count_digits(val):

count_lst = [0] * 10

val = str(val)

for digit in val:

if digit == "0":

count_lst[0] += 1

elif digit == "1":

count_lst[1] += 1

elif digit == "2":

count_lst[2] += 1

elif digit == "3":

count_lst[3] += 1

elif digit == "4":

count_lst[4] += 1

elif digit == "5":

count_lst[5] += 1

elif digit == "6":

count_lst[6] += 1

elif digit == "7":

count_lst[7] += 1

elif digit == "8":

count_lst[8] += 1

elif digit == "9":

count_lst[9] += 1

return count_lst

Step-by-step explanation:

Create a function called count_digits that takes one integer parameter, val

Initialize a count_list that will hold the counts for the digits in the val

Convert val to string

Initialize a for loop that iterates through the val

Inside the loop, check each digit in val and increment its corresponding position in the count_list

When the loop is done, return the count_list

User Joe Bowbeer
by
5.1k points