-7

我正在为我的编程课做一个项目,这是我正在努力的 5 件事。谢谢你的帮助!

  1. 有效单词列表将在 words.txt 中提供
  2. 要求只接受 2-8 个字母组合的输入
  3. 前任。输入将是“马球”
  4. 从 words.txt 中查找此输入的所有可能的有效单词
  5. 可能的结果,“poo”“pool”“loop”“polo”

    import random
    import itertools
    
    file_name='words.txt'
    DEBUG=True
    
    def load_words():
        try:
            f=open(file_name,'r')
            str1=f.read()
            f.close()
        except:
            print('Problem opening the file',file_name)
        list1=[]
        list1=str1.split()
        if DEBUG:
            length=len(list1)
            print('Number of words is',length)
            print(list1[0],list1[length//2],list1[-1])
            for i in range(10):
                print(list1[random.randint(1,length)])
        return(list1)
    
    def is_valid(str1,list1):
        valid=False
        count=0
        if str1 in list1:
            valid=True
        return valid
    
    def generate(letters):
        print(len(letters))
        count=1
        answers=[]
        for length in range(2,len(letters)+1):
            for x in itertools.permutations(letters,length):
                word=''
                for let in x:
                    word+=let
                print(word)
                if is_valid(word):
                    answers.append(word)
                count+=1   
            print(count,x)
            return(answers)
    
    def main():
        words=load_words()
        generate('abcde')
        guess=input('Check a word')
        if is_valid(guess.upper(),words):
            print(guess,'is a real word')
        else:
            print(guess,'is not a real word')
    
    main()
    
4

1 回答 1

1

就错误而言, print(list1[random].randint(1,length)) 应更改为 print(list1[random.randint(1,length)])

于 2011-11-30T17:37:26.433 回答