就剩这个了学校作业中的一题试过dict那种方法对数字string无法运行题目里面建议的方法不会求教Writeafunctionthatcountstheoccurencesofeachdigitinastringofnumbersusingthefollowin...
就剩这个了 学校作业中的一题
试过dict那种方法对数字string无法运行
题目里面建议的方法不会求教
Write a function that counts the occurences of each digit in a string of numbers using the following header:
def countdigits(aString):
The function countdigits counts how many times a digit appears in aString. The return value of the function is a list of 10 elements, each of which holds the count for a digit. For example after executing count(“122033”), the function returns the following list:
[1,1,2,2] #returned by countdigits
Assuming we refer to this list by the variable result, the list contains these numbers because:
result[0]=1 means 0 occurs 1 time in aString
result[1]=1 means 1 occurs 1 time in aString
result[2]=2 means 2 occurs 2 times in aString
result[3]=2 means 3 occurs 2 times in aString
Hint: In order to implement the countdigit function, you may want to create an empty list of size 10 using the following code:
result = 10 * [0]
Write a main function that prompts the user to enter a string of numbers, calls the countdigit function and then using the result list (returned by the countdigit function) to display the number of occurrences of each digit in the string.
Sample Output:
Enter a string of numbers: 4567899678
4 occurs 1 time
5 occurs 1 time
6 occurs 2 times
7 occurs 2 times
8 occurs 2 times
9 occurs 2 times
Another Sample Output:
Enter a string: 1222222333344499
1 occurs 1 time
2 occurs 6 times
3 occurs 4 times
4 occurs 3 times
9 occurs 2 times
NOTE:
In the output, when the number is more than 1, we print “times” else we print “time”.
You may assume that the user always enters positive numbers when asked for input. Input validation is not required.
The template for the program is as follows:
def countdigits(aString):
#Write the function code here
def main():
#Write the main function
#Call the main function
main()
展开