how can i design an algorithm to make sequential search with python ?
时间: 2024-01-11 11:02:58 浏览: 24
To design an algorithm for sequential search (also known as linear search) in Python, you can follow these steps:
1. Take an input list and the value to be searched.
2. Traverse the given list one by one and compare each element with the given value.
3. If the element matches with the given value, return the index of that element.
4. If the entire list is traversed and the element is not found, return -1.
Here is a sample code implementation of sequential search in Python:
```python
def sequential_search(arr, x):
"""
:param arr: list of elements to search
:param x: element to search for
:return: index of element if found, -1 otherwise
"""
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
```
You can call this function by passing the list and the value to be searched as parameters. For example:
```python
my_list = [1, 3, 5, 7, 9]
search_value = 7
result = sequential_search(my_list, search_value)
if result == -1:
print("Element not found in the list")
else:
print("Element found at index", result)
```
Output:
```
Element found at index 3
```
I hope this helps!