需要帮助来修复Python中的递归二进制搜索功能

时间:2019-04-07 17:04:57

标签: python binary-search

当我运行此函数时(通过将上下限设为0和len(list)-1),它可以正常工作。但是当键不在search_list中时,我得到一个严重的错误。有什么办法解决这个问题,使它说在列表中找不到名称/密钥?

def binary_search_recursive(search_list, key, lower_bound, upper_bound):
    middle_pos = (lower_bound + upper_bound) // 2
    if search_list[middle_pos] < key:
        binary_search_recursive(search_list, key, middle_pos + 1, upper_bound)
    elif search_list[middle_pos] > key:
        binary_search_recursive(search_list, key, lower_bound, middle_pos - 1)
    else:
        print('Key is at Position', middle_pos)

1 个答案:

答案 0 :(得分:1)

您需要解决下界大于上限并从函数返回时发生的边缘条件。这意味着找不到该值。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

wait = WebDriverWait(driver, 10)

def check_exists_by_xpath(xpath,wait):
    try:
        wait.until(EC.visibility_of_element_located((By.XPATH,(xpath)))
    except NoSuchElementException:
        return False
    return True
  

未找到