Created
September 17, 2020 16:38
-
-
Save PANDATD/4aca8bccd91b93cf9fd37f326046acc6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/python3 | |
| import os | |
| import time as t | |
| #this import is not being used | |
| from time import sleep | |
| os.system("clear") | |
| def lsearch(array:list, search_element:any)->None: | |
| #I commented the lines with sleep to be fair on the timing below | |
| #t.sleep(0.1) | |
| print("\nMethod:linear search") | |
| #t.sleep(0.1) | |
| print("You entered: ",list(array),type(array)) | |
| #t.sleep(0.1) | |
| print("Search Element is: ",search_element,type(search_element)) | |
| #t.sleep(0.1) | |
| print("Searching started ") | |
| #t.sleep(0.1) | |
| print("Checking..") | |
| # variable i is not required as it is handled by the for loop | |
| i = 0 | |
| for i in range(len(array)): | |
| if array[i] == search_element: | |
| #t.sleep(0.1) | |
| print("Element is Found at", i,"th index and", i+1, "th position") | |
| #t.sleep(0.1) | |
| print("Completed chacking. ") | |
| #t.sleep(0.1) | |
| print("Searching ended") | |
| break | |
| # else statement is not required here 'cause above you a have a break | |
| else: | |
| pass | |
| # you are recalculating the size of the array why not save that value, | |
| # in a variable before starting the loop | |
| if i==len(array)-1: | |
| #t.sleep(0.1) | |
| print("Element not found ") | |
| #t.sleep(0.1) | |
| print("Completed chacking.") | |
| #t.sleep(0.1) | |
| print("Searching ended") | |
| # why will you need to increment i variable value? | |
| # its value is handled by the for loop | |
| i = i+1 | |
| def lsearch_v2(array:list, search_element:any)->None: | |
| size = len(array) | |
| found = False | |
| for i in range(size): | |
| if array[i] == search_element: | |
| found = True | |
| break | |
| if found: | |
| print("Element is Found at"+ str(i) +"th index and"+ str(i+1)+ "th position") | |
| else: | |
| print("Element not found ") | |
| t1 = t.perf_counter() | |
| #lsearch doesn't return a result so no need to variable holding that result | |
| l1 = lsearch([1,2,3,4,5,6,7],'tejas') | |
| l2 = lsearch(['tejas','kunal','vignesh','datta','saif'],5) | |
| l3 = lsearch(['appale',1,2,3,'mango'],1) | |
| print("Time for first approach: %f" % (t.perf_counter() - t1)) | |
| t1 = t.perf_counter() | |
| lsearch_v2([1,2,3,4,5,6,7],'tejas') | |
| lsearch_v2(['tejas','kunal','vignesh','datta','saif'],5) | |
| lsearch_v2(['appale',1,2,3,'mango'],1) | |
| print("Time for second approach: %f" % (t.perf_counter() - t1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment