Здесь буквы (случайная_строка при вызове) — это строка из 10 символов, сгенерированная мной, а word_list (filtered_word) — это список всех слов на испанском языке, состоящих из 10 или менее букв.
Код: Выделить всё
def find_longest_word(letters, word_list):
# Sort word_list by length (longest to shortest)
word_list.sort(key=len, reverse=True)
# Convert word_list to a set for fast lookup
word_set = set(word_list)
longest_word = ''
max_length = 0
# Iterate over lengths from len(letters) down to 1
for length in range(len(letters), 0, -1):
# Filter word_list to include only words of current length
filtered_words = [word for word in word_list if len(word) == length]
# Generate permutations of current length
for perm in permutations(letters, length): #permutations() given letter set and length gives all permutations
#the outer for loop will make it so that we start by 10 letter words and after obtaining all permutations of that length we go to 9
perm_word = ''.join(perm)
if perm_word in filtered_words:
if length > max_length:
max_length = length
longest_word = perm_word
# Exit the loop once the longest word is found
return longest_word
return longest_word
longest_word = find_longest_word(random_string, filtered_words)
https://github.com/Albertofma/Letras весь проект на случай, если кто-то захочет увидеть остальную часть кода.
Подробнее здесь: https://stackoverflow.com/questions/786 ... -a-list-of