knowing when to say, I'm wrong

I did a that bit on Khan today, and thought for sure there was a different better way.... 
But after hours (all day),  What I came up with was just NOT better, and it was messy and just full of ways it can fail.

So,  know when to say,  NOPE...  that way is better. 
# lesson learned -again-

Example:  A binary spin off I did.  Khan Academy was JavaScript, but I flipped it to python to play with it.


####  my code:  ####
def binarySearch(alist, searchitem):
max_v = len(alist) - 1
startpoint = max_v//2
count = 0
factor = 2
x = 0 + startpoint
# 1(10x.5-5)  2(10x.5 - 3)  3   4     5(10x.5)     6    7   8(10x.5 + 3)  9  10(10x.5+5)
while count < startpoint:
count += 1
midpoint = x 
current = alist[midpoint]
if current == searchitem:
#print("*" * 15)
print(f"searchitem found : count = {count}")
return midpoint
elif current < searchitem:
y = x + startpoint//factor + 1
if y > max_v:
x = max_v
else:
x = x + startpoint//factor + 1
factor = factor * 2

else:
y = x - (startpoint//factor) - 1
if y < 0:
x = 0
else:
x = x - (startpoint//factor) - 1
factor = factor * 2
return None

# 73 - 43 - 2 = 28 lines


#####  Khan Academy code:  #####
def binarySearch2(alist, keyitem):
min_v = 0
max_v = len(alist) - 1
count = 0
while min_v <= max_v:
midpoint = (max_v + min_v)//2
print(midpoint)
print(f"max = {max_v} :  min = {min_v}")
count += 1
if alist[midpoint] == keyitem:
print(f"keyitem found count = {count}")
return midpoint
elif alist[midpoint] < keyitem:
min_v = midpoint + 1
print('lesser')
else:
max_v = midpoint - 1
print('greater')
return None

Comments

Popular posts from this blog

playing with color in powershell python

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame