Why does my Python spell checker only process the last word?
Asked by
nine tiny stitches
I'm building a spell checker that reads words from a text file and compares each one with an alphabetically sorted dictionary file using binary search. Words that are not found should be added to an `absent` list and printed at the end. However, the program appears to compare only the last word from the text file. I'm also unsure whether my `present` and `absent` updates are indented correctly and whether the binary search is implemented properly. What needs to be changed?
Answers
Use the `found` flag to decide which list receives the word. Right now the code appears to append the word to `present` and `absent` regardless of whether it was found. The structure should be roughly: `for word in firstLst:`, perform the binary search, then `if found: present.append(word)`, otherwise `absent.append(word)`. Also print both lists after the outer loop, not during every iteration.
Reply to this answer
First, make sure the indentation is preserved when sharing and running the code. In Python, indentation determines whether the loops and list updates are inside the outer loop. The search should run once for every word in `firstLst`, and the result should be appended only after that word's binary search finishes.
Reply to this answer
There is also an off-by-one issue in the search. With `while lo < hi`, the final remaining dictionary item may never be checked. Use `while lo <= hi`, set `mid = (lo + hi) // 2`, and move the bounds with `lo = mid + 1` or `hi = mid - 1`. After the loop, check the `found` flag before classifying the word.
Reply to this answer
Add temporary output inside the outer loop to see which word is being searched and what `lo`, `hi`, and `mid` contain. That will show whether the file-reading loop is collecting every word and whether the binary search is running for each one. If only the final word is processed, the likely cause is that the outer loop or the list updates are indented outside the loop.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions