KnowledgeBoat Logo
|

Computer Science

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.

Python Searching

1 Like

Answer

def lsearch(list1, key):
    for k in range(0, len(list1)):
        if key == list1[k]:
            return k
    return -1
list1 = eval(input("Enter the list: "))
for i in range(3):
    item = int(input("Enter item to be searched for: "))
    pos = lsearch(list1, item)
    if pos == -1:
        print(item, "not found")
    else:
        print(item, "found at index", pos)
Output
Enter the list: [32, -5, 34, 45, -6, 78, 87, 12, -9, 10]
Enter item to be searched for: -5
-5 found at index 1
Enter item to be searched for: 10
10 found at index 9
Enter item to be searched for: 100
100 not found

Answered By

1 Like


Related Questions