English

Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value. Apply linear search to find whether the key is present in the list or not. If the key

Advertisements
Advertisements

Question

Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value. Apply linear search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different keys and note the result.

Answer in Brief
Advertisements

Solution

def linearSearch(list, key):
 for index in range(0,len(list)):
  if list[index] == key: 
    return index+1 
 return None 
list1 = [] 
maximum = int(input("How many elements in your list? "))
print("Enter each element and press enter: ") 
for i in range(0,maximum):
 n = int(input())
 list1.append(n) 
print("The List contents are:", list1)
key = int(input("Enter the number to be searched:")) 
position = linearSearch(list1, key)
if position is None:
 print("Number",key,"is not present in the list") 
else:
 print("Number",key,"is present at position",position)
shaalaa.com
Linear Search in Python
  Is there an error in this question or solution?
Chapter 6: Searching - Exercise [Page 94]

APPEARS IN

NCERT Computer Science [English] Class 12
Chapter 6 Searching
Exercise | Q 3. | Page 94
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×