UPDATED RE: ps5_ghost Did anyone use just a binary search? I think I've been looking at it too long. I can't figure out what to do when a word in the list starts with the fragment (the users' string). _________ Well, I figured it out finally. The fragment is always less than any word starting with it, so when I was doing the binary search, I was left with 2 alternatives that did not include words starting with the fragment. Anyway, here is the search part of my program for anyone going the same route! http://pastebin.com/PXpvB1Qr
@dbwonders, I was working on the same problem but couldn't figure out how to check if a word in the list starts with the fragment. Your solution was really helpful :). I am however confused with the line: elif fragment(frag, wordlist[last+1]) == False: While it works in most of the cases, it might not work in some. For instance if the fragment is "zz" (if you accept "zzz" as a word).
You are right. zzz is the last word of the wordlist as well as wordlist[last], so wordlist[last+1] is out of range. I added: elif wordlist[last]==wordlist[-1]: if fragment(frag,wordlist[last]) == False: return False to catch that exception--which I hope is the only one! Well spotted...Cheers.
Great, it works. :) Also I tested this code with a word list of just 26 words (each word starting with a unique letter from a-z). In that case, wordlist[last+1] wont work coz the next word begins with a unique letter and the output will be something like, "Player 1 loses because no word begins with B". (If you start with "b", wordlist[last+1] would be "cat"). So, I made the following addition: elif fragment(frag, wordlist[last+1]) == False and fragment(frag,wordlist[last])==False: return False This way the code should work regardless of the list you use. I have attached the word list with 26 words below.
I just realized, there's still something missing in the previous change I mentioned. For example, if the players enter character in the order AZYGOUS, there will be an error. In this case, the output looks like this: 4622 4623 ba azygou 4622 azygous Player 2 loses because no word begins with AZYGOU Neither wordlist[last] nor wordlist[last+1] begin with AZYGOU. But, wordlist[mid] does. So, the previous piece of code should be: elif fragment(frag, wordlist[last+1]) == False and fragment(frag,wordlist[last])==False and fragment(frag,wordlist[mid])==False: return False
Makes for an awfully long line, doesn't it? Funny thing is, I distinctly remember having the wordlist[mid] in my code, then taking it out because I couldn't remember why I had it there in the first place! The wordlist[last] was a good catch...makes perfect sense. Lesson learned: better notes and better testing next time....Thanks
Yeah it's quite long but works(hopefully) for every possible condition. :)
Join our real-time social learning platform and learn together with your friends!