如果一个单词的匹配索引与列表中所有其他单词的索引如何匹配,只有当其他任何单词中的第一个单词的所有索引匹配时才会返回

时间:2017-09-23 09:49:34

标签: python python-2.7 python-3.x list match

我正在尝试用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

的组合

所以我的论文算法是我写的:

enter image description here

根据该算法,我能够执行到第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)

由于模式正在重复,所以我试图实现递归方法,但这不起作用。

1 个答案:

答案 0 :(得分:0)

忽略订单

看起来你不关心信件的位置。在这种情况下,您只需要检查word1word2中的字母是否与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

效率不高,但它适用于您的示例。

考虑订单

如果考虑到订单,您可以将::21::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