मराठी

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

प्रश्न

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.

थोडक्यात उत्तर
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 6: Searching - Exercise [पृष्ठ ९४]

APPEARS IN

एनसीईआरटी Computer Science [English] Class 12
पाठ 6 Searching
Exercise | Q 3. | पृष्ठ ९४
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×