如何在文件中进行线性搜索?

2024-10-01 07:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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")

Tags: 文件theinnumberisposition数字fname
1条回答
网友
1楼 · 发布于 2024-10-01 07:19:26

您得到的答案是错误的,因为您正在比较string和{}

您的intListstring的列表,而不是{}。您在接受输入时正在将{}解析为int。删除int解析,字符串将匹配。在

mynum=input("What is the number you are looking for in the file?")

另外,如果您期望print("The number is in index: ",aList)将打印与字符串匹配的索引,那么您将无法获得正确的输出,因为它显示的是输入列表,而不是包含索引的列表。在

相关问题 更多 >