Page 355 - Computer Science Class 11 With Functions
P. 355
07 '''
08 if len(lst1) == 0 :
09 return []
10 else:
11 cumLst = [lst1[0]] # lst1[0] is sum of 1-element list
12 for i in range(1,len(lst1)):
13 nextElement = cumLst[i-1] + lst1[i]
14 cumLst.append(nextElement)
15 return cumLst
16 # Objective: To find the cumulative sum of elements of an integer list
17 myList = eval(input('Enter a list of numbers: '))
18 result = cumulativeList(myList)
19 print('List of cumulative sums: ' ,result)
Sample Output:
>>> Enter a list of numbers: [1,2,5,2,5]
List of cumulative sums: [1, 3, 8, 10, 15]
4. Develop linearSearch(myTuple, key) that searches a tuple linearly for the required key. It should
take a tuple myTuple and a value key to be searched in myTuple as arguments. When the key is present in
myTuple, the function linearSearch should return True and the index where the search key is found. If
linearSearch reaches the end of the list without finding the key, linearSearch should return False
with None as the index.
01 def linearSearch(myTuple, key):
02 '''
03 Objective: To search the key in myTuple
04 Input Parameters:
05 myTuple: tuple
06 key : element to be searched
07 Return Value:
08 True: if key is found in the tuple, False otherwise
09 index:
10 if search succeeds, index of search key found
11 None, if search fails
12 '''
13 found = False
14 for index in range(len(myTuple)):
15 if myTuple[index] == key:
16 found = True
17 return found, index
18 return found, None
19
20 #main program segment
21 '''
22 Objective: To search for a key in a tuple
23 User Interface:
24 1. User is prompted to enter a tuple.
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)
Lists and Tuples 353

