该程序的目的是生成一个给出6个随机生成的字母表的字谜。语法似乎是正确的但是有一些我无法弄清楚的逻辑错误。如果你执行程序那么它只会继续跑步,&不要停止。我不认为它是因为任何无限循环,而是因为它无法使用6个生成的字母找到字谜。也许,我犯了一个愚蠢的错误,但请指出它。我突出了部分我认为有错误。如果你能帮助我,我会很高兴的。 可以从http://thinkpython.com/code/words.txt
下载文件words.txtimport random
def game():
while True:
ch=[]
res=[]
print 'The 6 randomly generated alphabets are :'
for i in range(6):
ch.append(chr(random.randrange(97,123)))
print ch,'\n'
delimiter=''
z=delimiter.join(ch) #converted list to a string
word_list2=dict() #word_list2 is a dictionary containing randomly generated letters as keys
for c in z:
if c not in word_list2:
word_list2[c]=1
else:
word_list2[c]=word_list2[c]+1
fin=open('words.txt')
for c in range(130000):
words=fin.readline()
word=words.strip()
flag=1
if len(word)==6:
word_list1=dict() #word_list1 is a dict containing char present in word as keys
for c in word:
if c not in word_list1:
word_list1[c]=1
else:
word_list1[c]=word_list1[c]+1
***for c in word_list2:
if c not in word_list1:
flag=1
break
else:
if word_list1[c]==word_list2[c]: #comparing if characters in both dict have same no. i.e 'a' should occur 2 times in both etc
flag==0
else:
flag=1
break***
if flag==0:
res.append(word)
if not res:
print 'the list is empty'
print 'Selecting a new set of randomly generated characters\n'
else :
print res
break
game()
答案 0 :(得分:0)
我终于弄明白了怎么做.....感谢你的帮助。这是有效的代码
def is_anagram(s,t):
x=dict()
y=dict()
for c in s:
if c not in x:
x[c]=1
else:
x[c]=x[c]+1
for c in t:
if c not in y:
y[c]=1
else:
y[c]=y[c]+1
for c in x:
if c not in y:
flag=1
break
else:
if x[c]==y[c]:
flag=0
else:
flag=1
break
if flag==0:
return 0
else:
return 1
import random
def game():
while True:
ch=[]
res=[]
print 'The 6 randomly generated alphabets are :'
for i in range(6):
ch.append(chr(random.randrange(97,123)))
print ch,'\n'
delimiter=''
z=delimiter.join(ch) #converted list to a string
fin=open('words.txt')
for c in range(130000):
val=1
words=fin.readline()
word=words.strip()
flag=1
if len(word)==6:
val=is_anagram(z,word)
if val==0:
res.append(word)
if not res:
print 'the list is empty'
print 'Selecting a new set of randomly generated characters\n'
else :
print res
break
game()