Linear search/searching for a word in a file/list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Linear search/searching for a word in a file/list (/thread-16646.html) |
Linear search/searching for a word in a file/list - kietrichards - Mar-08-2019 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") RE: Linear search/searching for a word in a file/list - Larz60+ - Mar-08-2019 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:
RE: Linear search/searching for a word in a file/list - kietrichards - Mar-08-2019 Oh but you see. You used "in". And I can't do that. That's an exercise. :( RE: Linear search/searching for a word in a file/list - Larz60+ - Mar-08-2019 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))
|