Why does my Python spell checker only process the last word?

0
0
Asked By MellowCedar42 On

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?

4 Answers

Answered By CopperLynx6 On

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.

Answered By NovaTide53 On

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.

Answered By PixelHarbor7 On

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.

Answered By QuietMaple_18 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.