如何使用排列来查找输入中的所有可能单词?

时间:2011-11-30 17:08:57

标签: python permutation itertools

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

  1. 有效字词列表将在words.txt
  2. 中提供
  3. 要求输入仅接受2-8个字母的组合
  4. 实施例。输入将是“polo”
  5. 从words.txt
  6. 中查找此输入的所有可能有效单词
  7. 可能的结果,“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()
    

1 个答案:

答案 0 :(得分:1)

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