Q. 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 :-

def linearSearch(list, key):
    for index in range(0,len(list)):
        if list[index] == key:
            return index+1
            return None

lst = eval( input("Enter a List of mix of  10  negative  and  positive number :- "))

while True :
    key = int(input("Enter Key :- "))
    position = linearSearch(lst, key)
    if position is None:
        print("Number",key,"is not present in the list")
    else:
        print("Number",key,"is present at position",position)
    choice = input("Do you want to quit (Y/N) :- ")
    if choice == "Y" or choice == "y" :
        break

Output:-

Enter a List of mix of  10  negative  and  positive number :- [-5,9,-4,8,2,3,5,-9,1,-1]
Enter Key :- 1
Number 1 is present at position 9
Do you want to quit (Y/N) :-
n
Enter Key :- 5
Number 5 is present at position 7
Do you want to quit (Y/N) :-
n
Enter Key :- 10
Number 10 is not present in the list
Do you want to quit (Y/N) :-
n
Enter Key :- -4
Number -4 is present at position 3
Do you want to quit (Y/N) :-
y
>>>

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post