Page 406 - Computer Science V2.0 Class 11
P. 406
25 2. The user is asked to enter the key, and the program reports the search
26 result.
27 3. Search for keys continues so long as the user wants.
28 '''
29 myTuple = eval(input('Enter a tuple:\n'))
30 print('Contents of Tuple:', myTuple)
31 while True:
32 key = int(input('Enter the number to be searched:'))
33 found, index = linearSearch(myTuple, key)
34 if found:
35 print('Element',key,' is present in the tuple at index ', index)
36 else:
37 print('Element',key,' is not present in the tuple')
38 searchAgain = input('Continue another search? say Y/y for yes, N/n for no:')
39 if searchAgain != 'Y' and searchAgain != 'y':
40 break
Sample Output:
>>> Enter a tuple:
(4,5,2,3,4)
Contents of Tuple: (4, 5, 2, 3, 4)
>>> Enter the number to be searched: 4
Element 4 is present in the tuple at index 0
Continue another search? say Y/y for yes, N/n for no:y
>>> Enter the number to be searched: 2
Element 2 is present in the tuple at index 2
Continue another search? say Y/y for yes, N/n for no:y
>>> Enter the number to be searched: 10
Element 10 is not present in the tuple
Continue another search? say Y/y for yes, N/n for no:n
5. Write a function to count the frequency of each element in a tuple. Write a program that accepts a tuple of
integers and displays the count of frequency of each element in the tuple.
01 def countFrequency(myTuple):
02 '''
03 Objective: To count the frequency of each element in myTuple
04 Input Parameters:
05 myTuple: tuple
06 Return Value:
07 frequency: A list comprising (key, frquency) tuples
08 '''
09 frequency = []
10 uniqueMyTuple = set(myTuple)
11 for item in uniqueMyTuple:
12 frequency.append((item, myTuple.count(item)))
13 return frequency
14
15 #main program segment
16 '''
17 Objective: To count the frequency of each element in myTuple
18 User Interface:
19 User is asked to enter:
20 number of elements in the tuple
21 tuple elements one by one
22 '''
23 myTuple = eval(input('Enter a tuple\n'))
24 print('Tuple:', myTuple)
25 frequency = countFrequency(myTuple)
392 Touchpad Computer Science (Ver. 2.0)-XI

