RUN__IT # 二分查找python版

本文详细介绍了二分查找算法,包括其优点、缺点以及适用场景。提供了递归和非递归两种实现方式,并通过实例展示了如何查找有序数组中的特定元素。

⼆分查找⼜称折半查找,优点是⽐较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插⼊删除困难。

假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字⽐较,如果两者相等,则查找成功;否则利⽤中间位置记录将表分成前、后两个⼦表,如果中间位置记录的关键字⼤于查找关键字,则进⼀步查找前⼀⼦表,否则进⼀步查找后⼀⼦表。重复以上过程,直到找到满⾜条件的记录,使查找成功,或直到⼦表不存在为⽌,此时查找不成功。

递归实现

def binary_search(li,item):
    """二分查找 递归版"""
    n = len(li)
    # 当列表为空时,就返回没找到
    if n == 0:
        return False
    # 进行二分 
    mid = n // 2
    if item == li[mid]:    # 找到元素
        return True
    elif item < li[mid]:    # 在前半部分
        # 递归查找
        return binary_search(li[:mid],item)
    else:    # 在后半部分
        # 递归查找
        return binary_search(li[mid+1:],item)


if __name__ == '__main__':
    li = [1,12,14,17,22,24,25,28,33,35,42]
    print(binary_search(li,21))
    print(binary_search(li,14))

非递归实现

def binary_search(li,item):
    """二分查找 非递归"""
    start = 0
    end = len(li)
    while start <= end:
        # 进行二分
        mid = (start + end) // 2
        # 找到
        if item == li[mid]:
            return True
        # 在前半部分
        elif item < li[mid]:
            end = mid - 1    # 让end定位到mid的前一个位置,形成新列表
        else:    # 在后半部分
            # 让开始位置在后半部分,及mid的后一个位置
            start = mid + 1
    # 循环结束,不能再分时,还没找到,就返回False
    return False
      

if __name__ == '__main__':
    li = [1,12,14,17,22,24,25,28,33,35,42]
    print(binary_search(li,21))
    print(binary_search(li,14))
``` def _load_optimizer_state(self): main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint opt_checkpoint = bf.join( bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt" ) if bf.exists(opt_checkpoint): logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}") state_dict = dist_util.load_state_dict( opt_checkpoint, map_location=dist_util.dev() ) self.opt.load_state_dict(state_dict) def _setup_fp16(self): self.master_params = make_master_params(self.model_params) self.model.convert_to_fp16() def run_loop(self): lpip_loss = lpips.LPIPS(net="alex").to(dist_util.dev()) ############## ssim_loss = SSIM(win_size=7, win_sigma=1.5, data_range=1, size_average=False, channel=1) if parallel: radon_288_736 = para_prepare_parallel(2.5) radon_144_736 = para_prepare_parallel(4.5) radon_72_736 = para_prepare_parallel(8.5) radon_36_736 = para_prepare_parallel(16.5) else: radon_288_736 = para_prepare(2.5) radon_36_736 = para_prepare(16.5) helper = {"fbp_para_288_736": radon_288_736, "fbp_para_36_736": radon_36_736, "fbp_para_72_736": radon_72_736, "fbp_para_144_736": radon_144_736} ######################### "fbp_para_36_512": radon_36_51 while ( not self.lr_anneal_steps or self.step + self.resume_step < self.lr_anneal_steps ): batch, cond = next(self.data) timestep = np.random.randint(low=3, high=None, size=None, dtype=&#39;l&#39;) t = th.tensor([timestep,timestep]).to("cuda") if timestep == 2: cond["x_t"] = F.interpolate(F.interpolate(batch, (36, 736), mode="nearest"), (288, 736), mode="nearest") elif timestep == 1: cond["x_t"] = F.interpolate(F.interpolate(batch, (72, 736), mode="nearest"), (288, 736), mode="nearest") elif timestep == 0: cond["x_t"] = F.interpolate(F.interpolate(batch, (144, 736), mode="nearest"), (288, 736), mode="nearest") model_output = self.run_step(batch, cond, t, ssim_loss, lpip_loss, helper) # for i in range(2,-1,-1): # t = th.tensor([i,i]).to("cuda") # if i == 2: # cond["x_t"] = cond["low_res"] # model_output = self.run_step(batch, cond, t, ssim_loss, lpip_loss, helper) # else: # cond["x_t"] = model_output # model_output = self.run_step(batch, cond, t, ssim_loss, lpip_loss, helper) if self.step % self.log_interval == 0: logger.dumpkvs() if self.step % self.save_interval == 0: self.save() # Run for a finite amount of time in integration tests. if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0: return self.step += 1 # Save the last checkpoint if it wasn&#39;t already saved. if (self.step - 1) % self.save_interval != 0: self.save() def run_step(self, batch, cond, t, ssim_loss=None, lpip_loss=None, helper=None): model_output = self.forward_backward(batch, cond, t, ssim_loss, lpip_loss, helper) if self.use_fp16: self.optimize_fp16() else: self.optimize_normal() self.log_step() return model_output```解释代码内容
03-26
THRESHOLD = (0, 23, -24, 17, -10, 34) # Grayscale threshold for dark things... import sensor, image, time,ustruct from pyb import UART,LED #from pid import PID #rho_pid = PID(p=0.4, i=0) #theta_pid = PID(p=0.001, i=0) import pyb LED(1).on() LED(2).on() LED(3).on() sensor.reset() #sensor.set_vflip(True) #sensor.set_hmirror(True) sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQQVGA) # 80x60 (4,800 pixels) - O(N^2) max = 2,3040,000. #sensor.set_windowing([0,20,80,40]) sensor.skip_frames(time = 2000) # WARNING: If you use QQVGA it may take seconds clock = time.clock() # to process a frame sometimes. uart = UART(3,115200) #定义串口3变量 uart.init(115200, bits=8, parity=None, stop=1) # init with given parameters #识别区域 roi1 = [(0, 17, 15, 25), # 左 x y w h (65,17,15,25),#(30,0,20,15),#(0,0,80,60)]#停车 def outuart(x,a,flag): global uart; f_x=0 f_a=0 if flag==0: if x<0: x=-x f_x=1 if a<0: a=-a f_a=1 if flag==1: #十字 x,a,f_x,f_a=(0,0,0,1) if flag==2: #上左 x,a,f_x,f_a=(0,0,1,0) if flag==3: #上右 x,a,f_x,f_a=(0,0,1,1) if flag==4: #stop x,a,f_x,f_a=(1,1,1,2) #frame=[0x2C,18,cx%0xff,int(cx/0xff),cy%0xff,int(cy/0xff),0x5B]; #data = bytearray(frame) data = ustruct.pack("<bbhhhhb", #格式为俩个字符俩个短整型(2字节) 0x2C, #帧头1 0x12, #帧头2 int(x), # up sample by 4 #数据1 int(a), # up sample by 4 #数据2 int(f_x), # up sample by 4 #数据1 int(f_a), # up sample by 4 #数据2 0x5B) if flag!=1: uart.write(data); #必须要传入一个字节数组 else: for x in range(50): uart.write(data); #必须要传入一个字节数组 time.sleep_ms(1) p9_flag=0 #p9需检测从低变高 not_stop=0 while(True): clock.tick() img = sensor.snapshot().binary([THRESHOLD]) line = img.get_regression([(100,100)], robust = True) left_flag,right_flag,up_flag=(0,0,0) for rec in roi1: img.draw_rectangle(rec, color=(255,0,0))#绘制出roi区域 p = pyb.Pin("P9", pyb.Pin.IN) print(p.value()) if p.value()==0: p9_flag=1 if p.value()==1 and p9_flag==1: not_stop=1 p9_flag=0 if (line): rho_err = abs(line.rho())-img.width()/2 if line.theta()>90: theta_err = line.theta()-180 else: theta_err = line.theta() #直角坐标调整 img.draw_line(line.line(), color = 127) #画出直线 #print(rho_err,line.magnitude(),rho_err) if line.magnitude()>8: #if -40<b_err<40 and -30<t_err<30: #rho_pid直线左右偏移的距离,theta_err角度偏移 #rho_output = rho_pid.get_pid(rho_err,1) #theta_output = theta_pid.get_pid(theta_err,1) #output = rho_output+theta_output outdata=[rho_err,theta_err,0] print(outdata) outuart(rho_err,theta_err,0) if img.find_blobs([(96, 100, -13, 5, -11, 18)],roi=roi1[0]): #left #print(&#39;left&#39;) left_flag=1 if img.find_blobs([(96, 100, -13, 5, -11, 18)],roi=roi1[1]): #right #print(&#39;right&#39;) right_flag=1 if img.find_blobs([(96, 100, -13, 5, -11, 18)],roi=roi1[2]): #up #print(&#39;up&#39;) up_flag=1 #if not img.find_blobs([(96, 100, -13, 5, -11, 18)],roi=roi1[3]): #stop ##print(&#39;up&#39;) #stop_flag=1 if left_flag==1 and right_flag==1: outuart(0,0,1) #time.sleep_ms(5) print(&#39;shizi&#39;) continue if left_flag==1 and up_flag==1: outuart(0,0,2) print(&#39;up-left&#39;) continue if right_flag==1 and up_flag==1: outuart(0,0,3) print(&#39;up-right&#39;) continue #if stop_flag==1: #outuart(0,0,4) #print(&#39;stop&#39;) #continue #car.run(50+output, 50-output) else: #outuart(0,0,4) ##car.run(0,0) #print(&#39;stop&#39;) pass else: #car.run(50,-50) outuart(0,0,4) #if not_stop==1: #time.sleep_ms(1000) #not_stop=0 print(&#39;stop&#39;) #print(clock.fps())
最新发布
07-26
Base path: /home/fzk/ros_workspace Source space: /home/fzk/ros_workspace/src Build space: /home/fzk/ros_workspace/build Devel space: /home/fzk/ros_workspace/devel Install space: /home/fzk/ros_workspace/install #### #### Running command: "make cmake_check_build_system" in "/home/fzk/ros_workspace/build" #### CMake Warning (dev) in CMakeLists.txt: No project() command is present. The top-level CMakeLists.txt file must contain a literal, direct call to the project() command. Add a line of code such as project(ProjectName) near the top of the file, but after cmake_minimum_required(). CMake is pretending there is a "project(Project)" command on the first line. This warning is for project developers. Use -Wno-dev to suppress it. -- Using CATKIN_DEVEL_PREFIX: /home/fzk/ros_workspace/devel -- Using CMAKE_PREFIX_PATH: /home/fzk/ros_workspace/devel -- This workspace overlays: /home/fzk/ros_workspace/devel -- Found PythonInterp: /usr/bin/python3 (found suitable version "3.8.10", minimum required is "3") -- Using PYTHON_EXECUTABLE: /usr/bin/python3 -- Using Debian Python package layout -- Using empy: /usr/lib/python3/dist-packages/em.py -- Using CATKIN_ENABLE_TESTING: ON -- Call enable_testing() -- Using CATKIN_TEST_RESULTS_DIR: /home/fzk/ros_workspace/build/test_results -- Forcing gtest/gmock from source, though one was otherwise available. -- Found gtest sources under &#39;/usr/src/googletest&#39;: gtests will be built -- Found gmock sources under &#39;/usr/src/googletest&#39;: gmock will be built -- Found PythonInterp: /usr/bin/python3 (found version "3.8.10") -- nosetests not found, Python tests can not be run (try installing package &#39;python3-nose&#39;) -- catkin 0.8.0 -- BUILD_SHARED_LIBS is on -- BUILD_SHARED_LIBS is on -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- ~~ traversing 1 packages in topological order: -- ~~ - test_pkg -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- +++ processing catkin package: &#39;test_pkg&#39; -- ==> add_subdirectory(test_pkg) -- Could NOT find roscpp (missing: roscpp_DIR) -- Could not find the required component &#39;roscpp&#39;. The following CMake error indicates that you either need to install the package with the same name or change your environment so that it can be found. CMake Error at /usr/share/catkin/cmake/catkinConfig.cmake:82 (find_package): Could not find a package configuration file provided by "roscpp" with any of the following names: roscppConfig.cmake roscpp-config.cmake Add the installation prefix of "roscpp" to CMAKE_PREFIX_PATH or set "roscpp_DIR" to a directory containing one of the above files. If "roscpp" provides a separate development package or SDK, be sure it has been installed. Call Stack (most recent call first): test_pkg/CMakeLists.txt:10 (find_package) -- Configuring incomplete, errors occurred! See also "/home/fzk/ros_workspace/build/CMakeFiles/CMakeOutput.log". See also "/home/fzk/ros_workspace/build/CMakeFiles/CMakeError.log". make: *** [Makefile:320:cmake_check_build_system] 错误 1 Invoking "make cmake_check_build_system" failed
06-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值