Introduction:
In this Python code example, we’ll learn how to implement a linear search algorithm to check if a number is present in a list. Linear search is a basic search algorithm that sequentially checks each element in a list until a match is found or all the elements have been exhausted. We’ll define a function called `linearSearch()` that takes a number and a list as input and returns the position of the number if it is present in the list, or None if it is not.
Code:
#Function to check if a number is present in the list or not
def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
#end of function
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")
Logic:
- Define a function called `linearSearch()` that takes two parameters: `num` and `list1`.
- Iterate through the elements in the list using a `for` loop and the `range()` function.
- Check if the current element in the list is equal to the provided number (`num`).
- If a match is found, return the index (`i`) of the element in the list.
- If no match is found after iterating through all the elements, return None.
- Create an empty list called `list1`.
- Prompt the user for the maximum number of numbers they want to enter in the list.
- Use a `for` loop and the `input()` function to add the numbers to the list using the `append()` method.
- Prompt the user to enter the number they want to search for in the list.
- Call the `linearSearch()` function with the provided number and the list.
- Check if the result returned by the function is None.
- If it is, print a message stating that the number is not present in the list.
- If it is not None, print a message stating that the number is present at the position returned by the function.
Output:
>> How many numbers do you want to enter in the list:5
>> Enter a list of numbers:
1
2
3
4
5
Enter the number to be searched:4
Number 4 is present at 4 position