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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
