Skip to content

Added the linear search algorithm example #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions SearchingAlgorithms/Linear_Search.py
Original file line number Diff line number Diff line change
@@ -1 +1,33 @@

def linear_search(all_items, item):
"""Searches an item inside an iterable using the
linear search algorithm.

Positional Arguments:
all_items -- an iterable of items to search
item -- the item to find
"""
for index, element in enumerate(all_items):
if element == item:
return index
else:
return -1


import random

# Generating a random list with 25 integers
my_list = [ random.randint(0, 100) for _ in range(25) ]
print("List: ", my_list)

# Reading the number to find in list
item_to_find = int(input("Type the number to find: "))

# Executing the linear search algorithm
found_index = linear_search(my_list, item_to_find)

# Printing the results
if found_index > -1:
print("The {} was found at position {}!".format(item_to_find, found_index))
else:
print("The {} wasn't found!".format(item_to_find))