Python Tutorial
#!/usr/bin/python def linear_search(search_key, list_vals): for index, val in enumerate(list_vals): if search_key == val: return index; return -1; if __name__ == "__main__": list_vals = [10, 20, 30, 40, 50, 60, 70, 80]; key = int(raw_input("Please enter a string:")); print("key is found at index: %d" % linear_search(key, list_vals));Output:
$ python linear-search.py Please enter a string:10 key is found at index: 0 $ python linear-search.py Please enter a string:30 key is found at index: 2 $ python linear-search.py Please enter a string:50 key is found at index: 4 $ python linear-search.py Please enter a string:9 key is found at index: -1
#!/usr/bin/python def linear_search(search_key, list_vals): for index in range(0, len(list_vals)): if search_key == list_vals[index]: return index; return -1; if __name__ == "__main__": list_vals = [10, 20, 30, 40, 50, 60, 70, 80]; key = int(raw_input("Please enter a string:")); print("key is found at index: %d" % linear_search(key, list_vals));Output:
$ python linear-search.py Please enter a string:20 key is found at index: 1 $ python linear-search.py Please enter a string:30 key is found at index: 2 $ python linear-search.py Please enter a string:3 key is found at index: -1
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page