【发布时间】:2018-04-19 03:52:01
【问题描述】:
我是 python 新手,我的作业有问题。我想从一个位置读取一个文件并查找该文件中出现了多少次数字。我已经完成了您阅读文件并获取列表的位置。我还在程序中使用线性搜索来查找数字。但是,无论我做什么,我都会得到数字在列表中的答案。有谁可以帮我离开这里吗? 这是我的代码:
import os.path
fLocation="C://TEMP//"
print("Assumed file location is at: ", fLocation)
fName = input("\nPlease enter a file name with its extension (ex. XXX.txt): ")
try:
fin = open(fLocation + fName, 'r')
aStr = fin.read()
aList = aStr.split()
def linearSearch(intList,target):
found=False
position=0
while position<len(intList):
if intList[position] == target:
found=True
break
position=position+1
return found
mynum=int(input("What is the number you are looking for in the file?"))
filenum= linearSearch(aList, mynum)
if filenum:
print("The number is in index: ",aList)
else:
print("The number is not in the list")
【问题讨论】:
-
你应该学习如何调试你的 Python 代码。
-
一个明显的问题是您将输入转换为int,但没有以相同的方式转换文件中的单词,数字
42不等于字符串'42',因此您永远无法通过这种方式找到匹配项。 -
另外,这段代码也不会运行。至少有两个错误,在第二个错误之后我停止尝试修复它。 minimal reproducible example 必须可运行才能成为实际示例。您还需要包含一个小样本文件进行测试。没有人可以调试您的问题。如果你不让他们复制它。
标签: python linear-search