Question

with pythonWrite a function called linear search which consumes a sorted list of integers and a number and linearly searches for the number in the list. Your function should return how many comparisons were made in order to find the element in the list. If the element is not in the list, your linear search should return -1 Note: You must not check every element unnecessarily. You should terminate your loop when you can determine the element is no longer in the list. For example: Result Test alon. 1, 3, 4 print linear search (alon 3) alon 4 print linear search (alon 3)

0 0
Add a comment Improve this question Transcribed image text
Answer #1
"""

Author:
Date :3/5/17
File Name:linear_search.py
Description:

"""


def linear_search(data, item):
    """
    Return the index of element if found else -1
    :param data: 
    :param item: 
    :return: 
    """

    for i in range(len(data)):
        if data[i] == item:  # check if item is equal to data[i]
            return i+1
    return -1


if __name__ == '__main__':
    alon = [1, 3, 4]
    print(linear_search(alon, 3))

    alon = [4]
    print(linear_search(alon, 3))

output:

2 -1 Process finished with exit code 0

Add a comment
Know the answer?
Add Answer to:
with python Write a function called linear_search which consumes a sorted list of integers and a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT