[英]How to check if a certain word can be used for another word in Python
Peace,和平,
f.ex.:例:
ur word is "AAAaaaaa"
and you want to check what words u can create with it compared from another list.你的词是
"AAAaaaaa"
,你想检查你可以用它从另一个列表中创建什么词。
f.ex.前任in the list there is:
在列表中有:
AA
AAH
AAHED
AAHING
AAHS
AAL
AALII
AALIIS
AALS
So the only output should be "AA"
cause u can't create things where you miss letters.所以唯一的 output 应该是
"AA"
,因为你不能创建你错过字母的东西。
I got this so far, but it outputs every word in the list where a "A"
is included.到目前为止我得到了这个,但它会输出列表中包含
"A"
的每个单词。
with open("sowpods.txt", "r") as check: #TOWORK WITH
for line in check.readlines():
for x in word:
for y in line:
if x in y:
valid_words.append(line.strip())
I think you can adapt a logic like this:我认为您可以采用这样的逻辑:
s= "AAAaaaaa"
list =["AA","AAH", "AAHED","AAHING", "AAHS"]
valid_words=[]
flag = True
for i in range(0,len(list)):
for j in range (0,len(list[i])):
if list[i][j] in s :
continue
else:
flag = False
break
if flag :
print (list[i] + " exists")
valid_words.append(list[i])
you can use filter
你可以使用
filter
word = "ZZAAEE"
existing = ["AA", "AAH", "ZEZE", "AAHING", "AAHS"]
valid_words = []
def cmp_str(exist): # exist is one item in existing list
copy_word = str(word) # so to not modified the word
for c in exist:
idx = copy_word.find(c) # find the index of char in word
if idx == -1:
return False
copy_word = copy_word[:idx] + copy_word[idx+1:] # drop the match character
return True
valid_words = list(filter(cmp_str, existing)) # cmp_str is called by the filter function
print(valid_words)
PS: update the code as position of character should be ignored PS:更新代码为 position 字符应该被忽略
In [1]: words = ['ZIZ', 'ZIZZ', 'ZZI']
In [2]: w = "ZZAAI"
In [3]: for word in words:
...: match=False
...: chars = list(word)
...: for i in list(w):
...: if i in chars:
...: match = True
...: chars.remove(i)
...: else:
...: match=False
...: if len(chars) == 0:
...: print(word)
...: elif not set(chars).issubset(list(w)):
...: print(word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.