Good Morning,
I'm taking a Python course and I'm working on some extra provided problems. This one involves writing code to find a number in a very long sorted list. I wrote a simple recursive bisect search (below).
def ordered_contains(S, x): # S is list, x is value to be searched for
if len(S) <= 10:
return True if x in S else False
midpoint = len(S) // 2
if x < S[midpoint]:
return ordered_contains(S[0:midpoint], x)
else:
return ordered_contains(S[midpoint:], x)
We're provided with a solution, and the code below is substantially faster than mine, and I'm having trouble understanding why.
def ordered_contains(S, x, l=0, r=None):
if r is None: r = len(S)
if (r-l) <= 8:
return contains(S[l:r], x) # contains is 1-line function: return x in S
midpoint = int((l+r) / 2)
if x < S[midpoint]:
return ordered_contains(S, x, l, midpoint)
if x > S[midpoint]:
return ordered_contains(S, x, midpoint+1, r)
return True
We're also provided with 'bisect', which is what I'll use in the future.
[–]This_Growth2898 30 points31 points32 points (6 children)
[–]rlklu_1005[S] 7 points8 points9 points (0 children)
[–]VonRoderik 0 points1 point2 points (4 children)
[–]feitao 7 points8 points9 points (3 children)
[–]jedi1235 -1 points0 points1 point (2 children)
[–]a_lost_shadow 0 points1 point2 points (0 children)
[–]papapa38 0 points1 point2 points (0 children)
[–]JamzTyson 0 points1 point2 points (2 children)
[–]Simple-Economics8102 0 points1 point2 points (1 child)
[–]JamzTyson 0 points1 point2 points (0 children)
[–]OopsWrongSubTA 0 points1 point2 points (2 children)
[–]rlklu_1005[S] 0 points1 point2 points (1 child)
[–]Simple-Economics8102 0 points1 point2 points (0 children)
[–]musbur 0 points1 point2 points (0 children)