首页 > 解决方案 > 我可以用这些字符组成什么词?

问题描述

我有一个问题,如果我有一个包含 16 个字符的列表和一个包含 words 的 txt,我怎么知道这 16 个字符可以组成哪些单词?

重要:(不再重复)

例如:“smalu”

无法形成“小”字,因为缺少“L”

f = open ("twl06.txt", "r")
wordlist = ("a", "b", "c", "a", "r", "h", "k", "c", "i", "p", "h", "t", "r", "h", "k", "c")


while (True):
     line = f.readline () #For example "small"
     line2 = list(line)
     if line2 in wordlist: #Check if the word in line can be created with the characters that Wordlist has


         print (line) #Print the word that can be created
         print ("index of elements:" How do I do this?) #Print the index (in wordlist) of each character found

标签: pythonsearchword

解决方案


虽然,就像说的那样,我们不是代码编写或教程服务,但如果您想实现这一点,您可以执行以下操作:

wordlist = ["a", "b", "c", "a", "r", "h", "k", "c", "i", "p", "h", "t", "r", "h", "k", "c"]
words = open("twl06.txt", "r").read().split() #Get all words in a text file

for word in words: #Cycle through all words
  indexes = [] #Set indexes to be blank
  usedletters = [] #Set used letters to blank

  for letter in word: #Cycle through each letter in the words
    if letter in wordlist: #Check if litter is in the list of words
      indexes.append(wordlist.index(letter)) #Append the index of the letter to our list
      usedletters.append(letter)
      wordlist[wordlist.index(letter)] = 0 #Set curreent used letter to placeholder
  if len(indexes) == len(word): #Check if we found all the letters
    print(word) #print the word that was found
    print("index of elements:", indexes) #print the list of that words indexes
  else: #In case we didnt get all the letters
    for i in range(len(indexes)): #Cycle through all replaced indexes
      wordlist[indexes[i]] = usedletters[i] #Set them back to their original letters

推荐阅读