Ad
I Wanted To Do A Binary Search But The Result Is Faulty
I wanted to do binary search on a list but the result shows 'false' even if I check a number from the list.
def clist(a):
l = [2,6,5,9,7,1,4,8,3]
newl = sorted(l)
check = int(1+len(newl)/2)
if newl[check] == a:
return True
if check > a:
for x in newl[:check]:
if x == a:
return True
return False
if check < a:
for x in newl[check::]:
if x == a:
return True
return False
print(clist(7))
Ad
Answer
You could write your script in such a way that:
- take the element at the middle of the list
- return it if that's what you need
- if your
needle
is gt than the middle, then callbsearch
on the remaining right side of the list - othwewise call
bsearch
with the left side
def bsearch(needle, haystack):
l = len(haystack)
half = int(l / 2)
element = haystack[half];
if element == needle:
return element
if needle <= element:
return bsearch(needle, haystack[0:half])
if needle > element:
return bsearch(needle, haystack[half:l])
print(bsearch(7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
in binary search:
- list must be ordered
- as stated by @tripleee, you have to recursively split the list in halves
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad