2016-07-29 20:06:49 +00:00
|
|
|
"""
|
2020-03-04 12:40:28 +00:00
|
|
|
This is pure Python implementation of linear search algorithm
|
2016-07-29 20:06:49 +00:00
|
|
|
|
|
|
|
For doctests run following command:
|
|
|
|
python -m doctest -v linear_search.py
|
|
|
|
or
|
|
|
|
python3 -m doctest -v linear_search.py
|
|
|
|
|
|
|
|
For manual testing run:
|
|
|
|
python linear_search.py
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def linear_search(sequence, target):
|
2016-08-30 19:06:49 +00:00
|
|
|
"""Pure implementation of linear search algorithm in Python
|
2016-07-29 20:06:49 +00:00
|
|
|
|
2020-05-14 14:52:43 +00:00
|
|
|
:param sequence: a collection with comparable items (as sorted items not required in Linear Search)
|
2016-07-29 20:06:49 +00:00
|
|
|
:param target: item value to search
|
|
|
|
:return: index of found item or None if item is not found
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> linear_search([0, 5, 7, 10, 15], 0)
|
|
|
|
0
|
|
|
|
|
|
|
|
>>> linear_search([0, 5, 7, 10, 15], 15)
|
|
|
|
4
|
|
|
|
|
|
|
|
>>> linear_search([0, 5, 7, 10, 15], 5)
|
|
|
|
1
|
|
|
|
|
|
|
|
>>> linear_search([0, 5, 7, 10, 15], 6)
|
|
|
|
|
|
|
|
"""
|
|
|
|
for index, item in enumerate(sequence):
|
|
|
|
if item == target:
|
|
|
|
return index
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
user_input = input("Enter numbers separated by comma:\n").strip()
|
|
|
|
sequence = [int(item) for item in user_input.split(",")]
|
2016-07-29 20:06:49 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
target_input = input("Enter a single number to be found in the list:\n")
|
2016-07-29 20:06:49 +00:00
|
|
|
target = int(target_input)
|
|
|
|
result = linear_search(sequence, target)
|
|
|
|
if result is not None:
|
2020-04-24 10:34:18 +00:00
|
|
|
print(f"{target} found at position : {result}")
|
2016-07-29 20:06:49 +00:00
|
|
|
else:
|
2019-10-05 05:14:13 +00:00
|
|
|
print("Not found")
|