Page 380 - Computer Science Class 11 With Functions
P. 380
08 Approach:
09 For each word w in list
10 if w is in dictionary, increment its count
11 else add w to the dictionary with 1 as its count
12 '''
13 wordCount = dict()
14 for w in lst:
15 if w in wordCount:
16 wordCount[w] += 1
17 else:
18 wordCount[w] = 1
19 return wordCount
20
21 #Objective: To find frequency of words given in a list.
22 lst = eval(input('Enter the list: '))
23 print('Dictionary of word count:: ', wordCountDict(lst))
Sample Output:
>>> Enter the list: ["apple","banana","apple","apple","banana"]
Dictionary of word count:: {'apple': 3, 'banana': 2}
2. Can you use the function wordCountDict(lst)that you developed in a previous question to count the number
of occurrences of numbers in a list.
Answer: Yes, because the function does not make use of the fact that the objects in the list are strings. So, it is
applicable to any list of objects, including heterogeneous lists. However, the objects in the list should be immutable
because we are using them as keys in the dictionary.
Example:
>>> wordCountDict(['ab', 7, (2, 3, 4), 27, 7, 'ab', (2, 3, 4), (1, 2, 3)])
{'ab': 2, 7: 2, (2, 3, 4): 2, 27: 1, (1, 2, 3): 1}
>>> wordCountDict(['ab', 7, [2, 3, 4], 27, 7, 'ab', [2, 3, 4], {1:1, 2:4}])
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
wordCountDict(['ab', 7, [2, 3, 4], 27, 7, 'ab', [2, 3, 4], {1:1, 2:4}])
File "F:\DOWNLOADS\try1.py", line 15, in wordCountDict
if w in wordCount:
TypeError: unhashable type: 'list'
3. Write a function stateCapitalDict() that prompts a user to enter some states and capitals and outputs
a dictionary stateCapital. Make use of the function stateCapitalDict() to write a menu driven
program that does the following:
a. Create a dictionary of state capitals.
b. Accept from the user the name of the state, and find its capital. If the name of a state does not appear in the
dictionary, ask the user "Would you like to add the corresponding capital". If yes, accept state:capital pair and
add to the dictionary.
c. Accept from a user a city's name and find the state whose capital is the city entered by the user. Display appropriate
messages.
01 def stateCapitalDict():
02 '''
03 Input Parameter: None
04 Return Value: stateCapital - Dictionary containing state as keys and capital as values
05 '''
06
07 stateCapital = dict()
08 state = input('Enter state:')
09 capital = input('Enter capital:')
10 while state != '' and capital != '':
378 Touchpad Computer Science-XI

