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.
Program to perform Linear Search on a list of 10 numbers
def linearSearch(list1, key): for i in range(len(list1)): if list1[i] == key: return i return -1
Create an empty list
list1 = [] print("Enter 10 elements (mix of negative and positive numbers):") for i in range(10): n = int(input()) list1.append(n)
print("The List contents are:", list1)
Search for 3 different keys
for j in range(3): key = int(input("Enter the number to be searched: ")) position = linearSearch(list1, key) if position == -1: print("Number", key, "is not present in the list") else: print("Number", key, "is present at position", position + 1)
Sample Output:
Enter 10 elements (mix of negative and positive numbers):
-5 3 -12 7 -8 15 -3 9 -1 4
The List contents are: [-5, 3, -12, 7, -8, 15, -3, 9, -1, 4]
Enter the number to be searched: 7
Number 7 is present at position 4
Enter the number to be searched: -8
Number -8 is present at position 5
Enter the number to be searched: 10
Number 10 is not present in the list
Explanation
The program implements linear search algorithm which sequentially checks each element of the list until the key is found or the list ends. The function returns the index if found, otherwise returns -1. The position is displayed as (index + 1) since list indexing starts from 0. Three test runs demonstrate successful search for positive number (7), negative number (-8), and unsuccessful search for absent key (10).
Solution Steps
Step 1: Define linearSearch function that iterates through list and compares each element with key
Step 2: Create empty list and accept 10 numbers from user (mix of negative and positive)
Step 3: Accept key value and call linearSearch function
Step 4: Check return value - if not -1, display position; else display 'not present' message
Step 5: Repeat for 3 different keys to demonstrate working