Python二分查找函数print语句延迟输出问题求助
问题解答
这不是time.sleep的问题,而是Python的输出缓冲机制导致的。默认情况下,标准输出(stdout)会采用行缓冲或块缓冲策略,在部分环境中,缓冲会把所有print内容暂存起来,直到缓冲区满或程序结束才一次性输出。
解决方法很直接,给所有print语句加上flush=True参数,强制实时刷新缓冲区:
def start_search(self): check_count = 1 while not self.upper_bound == self.target_number: time.sleep(0.01) middle = self.get_half(self.lower_bound, self.upper_bound) print(f"checking between {self.lower_bound} and {self.upper_bound}", flush=True) if middle > self.target_number: print(f"Midpoint of {middle} is higher,", flush=True) self.upper_bound = middle elif middle < self.target_number: print(f"Midpoint of {middle} is lower,", flush=True) self.lower_bound = middle else: print(f"Found value at midpoint {middle} after {check_count} check(s)", flush=True) self.upper_bound = middle check_count += 1
另外提个小优化:找到目标值时直接用break退出循环,代码逻辑会更清晰,不用特意修改upper_bound:
else: print(f"Found value at midpoint {middle} after {check_count} check(s)", flush=True) break
内容的提问来源于stack exchange,提问作者Otis
相关产品推荐
相关产品推荐

