我可以请你帮忙吗?
我必须用python为homewrok编写一个程序,它要求两个竞争对手轮流给一个字母。当字典中没有这样的单词时,程序就结束了(我从老师那里导入了文本格式的字典)。
下面是它应该是什么样子:
竞争对手1,字母a: m 竞争对手2,字母b: o 竞争对手1,字母a: u 竞争对手2,字母b: s 竞争对手1,字母a: e 竞争对手2,字母b: i
字典里没有这样的词!
我就是这样开始的:
dictionary=open("dictionary.txt", encoding="latin2").read().lower().split()
a=input("Competitor 1, letter a:")
b=input("Competitor 2, letter b:")
word=a+b
while word in dictonary:
a=input("Competitor 1, letter a:")
word=word+a
b=input("Competitor 2, letter b:")
word=word+b
print("There is no such word" ,word, "in dictionary!")但有些地方不对劲。因为当我开始编程时,我会写前两封信。它说字典里没有这样的词。
请帮帮我!
还有一件事:游戏必须在第一个错误角色之后立即停止。你能告诉我怎么做这个吗?
发布于 2012-10-21 09:02:22
那是因为你的情况不对!您不应该检查word是否在字典中,而应该检查字典中是否有以word开头的单词!
这里有一个可能的解决方案(也许不是最漂亮的):
word_ok = True
dictionary=open("dictionary.txt", encoding="latin2").read().lower().split()
a=raw_input("Competitor 1, letter a:")
b=raw_input("Competitor 2, letter b:")
word=a+b
while word_ok:
word_ok = False
for dict_word in dictionary:
if dict_word.startswith(word):
word_ok = True
break
if word_ok:
a=raw_input("Competitor 1, letter a:")
word=word+a
b=raw_input("Competitor 2, letter b:")
word=word+b
else:
break
print("There is no such word" ,word, "in dictionary!")编辑:
好的,这是一种从其他答案中汇编出来的。注意,encoding不是内置open()函数的有效关键字参数。如果要指定编码,请使用codecs.open()。还请注意,单词检查是在while循环中完成两次的,在每个竞争者的输入之后。
import codecs
dictionary = codecs.open('dictionary.txt','r',encoding='latin2').read().lower().split()
# Word we will build
word = ''
while True:
letter = raw_input("C1: ")
word = word + letter
if not any(known_word.startswith(word) for known_word in dictionary):
break
letter = raw_input("C2: ")
word = word + letter
if not any(known_word.startswith(word) for known_word in dictionary):
break
print "There is no such word", word, "in dictionary!"发布于 2012-10-21 09:10:30
你的规则不一致。考虑一下这个游戏:
s # Not a word
su # Not a word
sun # Word
sund # Not a word
sunda # Not a word
sunday # Word游戏什么时候结束?
当字典中没有这样的单词时,程序就结束了。
你的规则说它应该在第一步结束,因为结果不是一个字。一个更好的规则是:
当字典中没有从输入开始的单词时,程序就结束了。
“轮流问两个竞争者”的实施也是错误的。你的程序要求两个竞争者都要一封信,然后检查单词。你想在玩家之间签下这个词。
dictionary = open("dictionary.txt", encoding="latin2").read().lower().split()
word = ""
c1turn = True
while any(knownword.startswith(word) for knownword in dictonary):
if c1turn:
letter = input("Competitor 1:")
else:
letter = input("Competitor 2:")
word = word + letter
c1turn = not c1turn
print("There is no such word", word, "in the dictionary!")发布于 2012-10-21 09:11:40
你必须改变你的状态。在这样做的过程中,您可以检查word是否在dictionary中是一个单词,而不是您想要的单词的一部分。你可以这样做:
while any(x.startswith(word) for x in dictionary): 通过这种方式,如果字典中位于同一位置的单词以True开头,则可以生成布尔值列表,其中每个元素都是word。如果字典中的任何单词以word开头,则条件为真,玩家应输入另一个字符。
https://stackoverflow.com/questions/12996372
复制相似问题