Search code examples
pythonlistfor-loopdivisionreadlines

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.

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.

I got this so far, but it outputs every word in the list where a "A" is included.

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

Solution

  • you can use 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