EdX平台Python猜数字习题判错求助:二分查找代码排查
二分查找猜数字代码排查问题
问题背景
你需要实现一个电脑通过二分查找猜数字的程序:用户心里想一个0(包含)到100(不包含)之间的整数,电脑给出猜测,用户输入h(猜高了)、l(猜低了)或c(猜对了)反馈,直到电脑猜中。你测试了83、8、42等数字都正常,但EdX平台判定代码错误,需要排查缺陷。
原始代码
high = 100 low = 0 correct = False response = "" user_number = input("Please think of a number between 0 and 100!") while (response != "c"): guess = int((high + low)/2) print("Is your secret number", guess, "?") response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly") if not (response == "h" or response == "c" or response == "l"): print("Sorry, I did not understand your input.") elif (response is "h"): high = guess elif (response is "l"): low = guess print ("Game over. Your secret number was:", guess)
代码缺陷分析
我找到了几个可能导致EdX判错的关键点:
字符串比较误用
is运算符:在Python中,判断字符串内容相等应该用==,is是用来判断两个对象是否为同一个内存实例的。虽然短字符串有时会因为Python的字符串驻留机制看起来能用is判断,但这不是可靠的写法——EdX的测试环境可能刚好触发了is判断不成立的场景,导致逻辑分支错误。你代码里的response is "h"和response is "l"必须改成response == "h"和response == "l"。冗余的输入与变量:你定义了
correct变量但全程没用到,属于无效代码;另外user_number = input(...)这一行完全多余——题目要求用户心里想数字,不需要输入,这行输入会干扰EdX的测试流程(比如测试脚本预期没有这个输入步骤,或者会错误处理这个输入内容)。浮点数转整数的不严谨性:
int((high + low)/2)在Python3中会先得到浮点数再转整数,虽然结果没问题,但更规范的做法是用整数除法(high + low) // 2,既避免不必要的浮点数转换,也更符合二分查找的整数操作逻辑。
修正后的代码
high = 100 low = 0 response = "" print("Please think of a number between 0 and 100!") while response != "c": guess = (high + low) // 2 print(f"Is your secret number {guess}?") response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly: ") if response not in ["h", "c", "l"]: print("Sorry, I did not understand your input.") elif response == "h": high = guess elif response == "l": low = guess print(f"Game over. Your secret number was: {guess}")
修正说明
- 替换
is为==,保证字符串比较的可靠性; - 移除冗余的
user_number输入和correct变量,让流程完全贴合题目要求; - 用整数除法
//优化猜测值的计算; - 用f-string优化输出格式,提升代码可读性。
这些修改应该能通过EdX的所有测试用例,你可以运行这个版本试试。
内容的提问来源于stack exchange,提问作者Aries
相关产品推荐
相关产品推荐

