Python 3.5 Write a program, dCount(lst,n) , which will take a 2-dimensional list
ID: 3862741 • Letter: P
Question
Python 3.5
Write a program, dCount(lst,n), which will take a 2-dimensional list which consists of a number (lst[i][0]) and string (lst[i][1]). The program will read each element in the list and create a dictionary entry with the number as the key and the string as the value until the number equals n. When the number (lst[i][0]) equals n, the program PRINTS the dictionary and RETURNS the length of the dictionary. If lst is empty, the dictionary will be empty and the length returned will be 0. It is possible that the list will not contain n in which case it will process through to the end of the list and print the dictionary and return the length as described.
You are required to use a while loop and you must check (you are NOT required to use a try/except)
dCount (II a [40 b [10 40 'b', 3 'a' ount 10) dCount (II a' 3: 'b', 4 'a', 5: c', 6 'q' c' 11, 10) q' 11, 10)Explanation / Answer
def dCount(lst,n):
listLen = len(lst) # store length of the list in a variable listLen
count = 0
finalDict = {} # variable to store the dictionary
while (listLen > 0): # run while loop until the entire list is read
if lst[count][0] == n: # check if the key in the list is equal to n
count = 0
break # break the loop if the key matches
else:
finalDict[lst[count][0]] = lst[count][1] # store key and value in the dictionary
count = count + 1 # increment the count so that it can loop through the entire list
listLen = listLen - 1 # decrement the length of the outer list
print finalDict # print the final dictionary
return len(lst) # return the length of the list
# testing sample are given below. If you run this script the output of the following test cases is printed
print dCount([[3, 'a'], [40, 'b'], [10, 'c']], 10)
print dCount([], 10)
print dCount([[4, 'a'], [3, 'b'], [5, 'c'], [6, 'q']], 10)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.