gpt4 book ai didi

python - 将字符串(任意顺序)与大数组中的字符串进行匹配

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:29 24 4
gpt4 key购买 nike

def Get_Word_List(File_=[]):
with open("Words.txt") as File: #File of 250k+ words separated via new line
for Line in File:
File_.append(Line.replace("\n",""))
return File_

def Get_Input(Str=str):
Str = raw_input("Input 7 letters: ")
while len(Str) != 7:
Str = raw_input("Input 7 letter: ")
return Str.upper()

def Find_Words():
Letters = Get_Input()
List = Get_Word_List() #An Array of strings, all in uppercase
for Word in List:
pass

我正在尝试以任意顺序匹配字符串(最大长度为 7),例如“ZZAFIEA”可以将“FIZZ”或“FEZ”赋予大小为 250k+ 的数组中的一个或多个单词,但我不能想办法做到这一点,我已经尝试了各种方法,感谢任何帮助

最佳答案

这是一个非常好的解决方案:

from collections import Counter


def counter_is_subset(x, y):
# If subtracting y from x doesn't return an empty Counter,
# x is NOT a subset of y.
return not (x - y)


def find_buildable_words(words, letters):
letters = Counter(letters)

for word in words:
if counter_is_subset(Counter(word), letters):
yield word


words = ['BLAH', 'FIZZ', 'FEZ', 'FOO', 'FAZE', 'ZEE']
letters = 'ZZAFIEA'

buildable_words = find_buildable_words(words, letters)

for word in buildable_words:
print(word)

在我的计算机上,对于 250,000 个单词的列表,运行时间约为 1.2 秒。

关于python - 将字符串(任意顺序)与大数组中的字符串进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com