Python实现Linear search线性搜索运行后无法输出预期结果如何排查
你代码的核心错误是类型不匹配:Python中input()函数默认返回字符串类型,而你用来对比的数组arr中存储的都是整数,字符串和整数做相等判断永远返回False,因此永远无法匹配到目标值。
修复方案
- 将输入的内容转换为整数类型,把第一行代码修改为:
n = int(input("enter a number: ")) - 额外说明:Python中语句末尾不需要加分号,原代码里
count = 0;的分号属于冗余写法,可直接删除。
修正后的完整可运行代码:
n = int(input("enter a number: ")) arr = [1,42,3,45,5] count = 0 for i in range(0, len(arr)): if arr[i] == n: count = count + 1 if count>0: print("found") else: print("not found")
内容的提问来源于stack exchange,提问作者Souvik Sen
相关产品推荐
相关产品推荐

