Ayodhyankit Paul Ayodhyankit Paul - 5 months ago 27
Python Question

How match index of one word to index of all other words in list return only if all index match of first word in other any word?

I am trying to solve a puzzle in python and the puzzle says :

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

so if i have a list :


in this list :

=> conbination of

=> cobination of

=> combination of

so my paper-algorithm what i wrote is :

enter image description here

according to that algorithm i am able to perform till step 2 but after step two how i match each index of one word with each other index of word , i could do this with zip module , finditer or nested loop but the thing is i don't have to match one same postion index like "iam"=="iam" , index can be in random position like "iam" will be "mia" , so how i can perform this problem ?

what i tried is buggy code and not working yet , i am sharing still


def hello(ae):
for i in ae:
yield i



def check(tr):
for i in tr:
for j in i:
if j in aq:


Since the pattern is repeating so I was trying to implement recursive approach, but that is not working.

Answer Source

Order is ignored

It looks like you don't care about letter positions. In that case, you only need to check if the letters from word1 and word2 sum up to the letters from goal. Since you don't care about position, it's enough to sort the letters:

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))

It outputs:

cold + shoe = schooled
boy + hair = iahroby
any + i = yani

It's not efficient but it works fine for your examples.

Order is taken into account

If order is taken into account, you can use zip to mix the words together. The goal word should have an even number of letters, and word1 and word2 should be both half as long as goal:

for goal in words:
    lg = len(goal)
    if lg % 2 == 0:
      for word1 in words:
          l1 = len(word1)
          if l1 == lg//2:
              for word2 in words:
                if len(word2) == l1:
                  if  ''.join(a+b for a,b in zip(word1,word2)) == goal:
                          print('%s * %s = %s' % (word1, word2, goal))

It outputs:

shoe * cold = schooled
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download