Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need explain about the code
#1
i worte this code:

import time

def search_lst(L, x):
    mone = 0
    for i in range(len(L)-1):
        if x == L[i]:
            return True
    return False
    
def binary_search(L, x):
    left = 0
    right = len(L) - 1
    while left <= right:
        mid = (left + right) // 2
        if x == L[mid]:
            return True
        else:
            if x < L[mid]:  # go to left half
                right = mid - 1
            else:  # go to right half
                left = mid + 1
    return False  # if we got here the search failed
    
lst = [3, 4, 5, 6, 9, 10, 13, 16, 18, 20, 22, 28, 29, 31, 32, 33, 40, 42, 47, 48, 50, 52]
start = time.perf_counter()
result = binary_search(lst, 52)
print(result)
end = time.perf_counter()
print(end-start)
s = time.perf_counter()
result = search_lst(lst,3)
print(result)
e = time.perf_counter()
print(s-e)

I wanted to compare the times of the functions.
But the second comparison (with the variables 'e' and 's') was negative and I wanted to know why?

Thanks.
Reply
#2
It's returns the seconds elapsed since a certain point in time. So the end values are larger than the start values. You want to reverse your second subtraction, so it matches the first one.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
It's e-s, not s-e in line 34.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Explain the python code in this definition Led_Zeppelin 1 748 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  I am new to python and Could someone please explain how this below code is working? kartheekdas 2 1,017 Dec-19-2022, 05:24 PM
Last Post: kartheekdas
  Explain the python code in this definition Led_Zeppelin 1 1,105 Oct-27-2022, 04:04 AM
Last Post: deanhystad
  Sudoku Solver in Python - Can someone explain this code ? qwemx 6 2,146 Jun-27-2022, 12:46 PM
Last Post: deanhystad
  Can someone explain this small snippet of code like I am a 5 year old? PythonNPC 3 1,247 Apr-08-2022, 05:54 PM
Last Post: deanhystad
  Could you explain each part of the code? Tsushida 2 1,517 Mar-20-2022, 08:19 AM
Last Post: Larz60+
  What is the run time complexity of this code and please explain? samlee916 2 2,305 Nov-06-2020, 02:37 PM
Last Post: deanhystad
  poplib - parsing message body, could somebody please help explain this code t4keheart 2 2,304 Oct-12-2020, 01:59 PM
Last Post: t4keheart
  Explain range in this code RavCOder 4 2,339 Oct-02-2019, 05:04 PM
Last Post: jefsummers
  Explain this code - for loop RavCOder 9 3,457 Sep-24-2019, 01:01 PM
Last Post: RavCOder

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020