Python Forum

Full Version: Linear search/searching for a word in a file/list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Guys, I have to make a program that and then asks user to input some word let's say (until user types STOP) and then checks if the word is in the list by linear search. And I can't use "in" operator here. This is so weird to me, can you give me some tips?
_________________________________
import sys

infile = open("ex5.acc", "r")

acc = ''
line = infile.readline()

while acc != "STOP":
   acc = input("Enter acc nr")
   line = infile.readline()
   if acc != line and acc != "STOP":
       print("It seems that there is no such accession nr in the file")
   elif acc == line:
       print("Accession number found")
print("Seems like you don;t want to search anymore")
def check_word(word, text):
    words = text.split()
    for item in words:
        if item == word:
            return True
    return False

line = "It seems that there is no such accession nr in the file"
print(check_word('accession', line))
print(check_word('dog', line))
output:
Output:
True False
Oh but you see. You used "in". And I can't do that. That's an exercise. :(
def check_word(word, text):
    idx = 0
    words = text.split()
    while True:
        try:
            if word == words[idx]:
                return True
            idx += 1
        except IndexError:
            return False
 
line = "It seems that there is no such accession nr in the file"
print(check_word('accession', line))
print(check_word('dog', line))
Output:
True False