Python- The Word Game "Ghost", File I/O, and List question
I want to create computer for the word-game Ghost. However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which 开发者_运维百科doesn't work):
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
I have demarcated the problem area in the code. I have no idea why it doesn't work. What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.
I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.
I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).
It is better to just make a new list. One possible way to do this is to replace the lines
for line in wordlist:
if not line.startswith(word):
wordlist.remove(line)
with
wordlist = [w for w in wordlist if w.startswith(word)]
Peter Norvig has a great discussion on autocorrect here:
http://norvig.com/spell-correct.html
The large-list comprehension and context matching seem relevant - and at 21 lines it's a quick read (with good explanation following). Also check out the "Charming python" 3-part on functional programming with python (IBM). You can do all the setup with a few list comprehensions.
If you want to work for ITA you'd be better off writing this in clisp... or clojure.
精彩评论