pythonfor-loopnested-loopswordle-game

How to use IN to check if an element is inside a string and avoid to compare duplicate element with Python


I have a string ORIGINAL = 'ready' and a word_list = ['error', 'radar', 'brave']. I use a nested forloop to check if each letter of every word in the word_list is in ORIGINAL. If True, modify the letter to '*", otherwise copy the letter. Here is the tricky part, let's say 'error', the first 'r' is inside 'error', how can I stop the forloop and move to the next non-duplicate letter? Below is the my code. Help need! Thanks. This is actually part of the algorithm behind WORDLE.

ORIGINAL = 'ready'
word_list = ['error', 'radar', 'brave']
result, modified_list = [], []
for word in word_list:
    for i in range(len(word)):
        if word[i] in ORIGINAL:
            l = '*'
        else:
            l = word[i]
        result.append(l)
    modified_list.append(''.join(result))
    result.clear()
print(modified_list)

Output:

['***o*', '*****', 'b**v*']

Desired output:

['**ror', '***ar', 'b**v*']


Solution

  • You can keep track of the letters in ORIGINAL that have already been seen.

    ORIGINAL = 'ready'
    word_list = ['error', 'radar', 'brave']
    result, modified_list = [], []
    for word in word_list:
        seen = []
        for i in range(len(word)):
            if word[i] in ORIGINAL and word[i] not in seen:
                l = '*'
                seen.append(word[i])
            else:
                l = word[i]
            result.append(l)
        modified_list.append(''.join(result))
        result.clear()
    print(modified_list)