我正在尝试用python解决一个难题,拼图说:
Two words “interlock” if taking alternating letters from each forms a
new word. For example, “shoe” and “cold” interlock to form “schooled.
interlocks word's characters can be random position ex : "iam" can be
"mia" now if "iam" and "boy” ==> combined word cab be yobmia
所以,如果我有一个清单:
a=["shoe","cold","schooled","any","boy","hair","iahroby","i","yani"]
在此列表中:
schooled
=> shoe
+ cold
iahroby
=> hair
+ boy
yani
=> any
+ i
所以我的论文算法是我写的:
根据该算法,我能够执行到第2步,但是在第二步之后我如何将一个单词的每个索引与单词的索引相匹配,我可以使用zip模块,finditer或嵌套循环执行此操作但事情是我不必像“iam”==“iam”那样匹配一个相同的位置索引,索引可以在随机位置,如“iam”将是“mia”,那么我怎么能解决这个问题?
我尝试的是有缺陷的代码而且还没有工作,我仍在分享
a=["shoe","cold","schooled","any","s","pre","our","uorpre"]
def hello(ae):
for i in ae:
yield i
ar=hello(a)
aq=list(ar.__next__())
def check(tr):
for i in tr:
for j in i:
if j in aq:
??
check(a)
由于模式正在重复,所以我试图实现递归方法,但这不起作用。
答案 0 :(得分:0)
看起来你不关心信件的位置。在这种情况下,您只需要检查word1
和word2
中的字母是否与goal
中的字母相加。既然你不关心位置,那就足以对字母进行排序:
words = ["shoe","cold","schooled","any","s","pre","our","uorpre"]
for goal in words:
lg = len(goal)
goal_letters = sorted(goal)
for word1 in words:
l1 = len(word1)
if lg > l1:
for word2 in words:
if word2 > word1 and len(word2) == lg - l1:
if sorted(word1 + word2) == goal_letters:
print('%s + %s = %s' % (word1, word2, goal))
输出:
cold + shoe = schooled
boy + hair = iahroby
any + i = yani
效率不高,但它适用于您的示例。
如果考虑到订单,您可以将::2
和1::2
分开,并检查这些是否为已知字词(感谢@StefanPochmann):
words = set(["shoe", "cold", "schooled", "any", "boy", "hair", "iahroby", "i", "yani"])
for goal in words:
word1 = goal[::2]
word2 = goal[1::2]
if word1 in words and word2 in words:
print('%s * %s = %s' % (word1, word2, goal))
# shoe * cold = schooled
输出:
shoe * cold = schooled