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

Time:03-01

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*']

CodePudding user response:

You could use a copy of the ORIGINAL word for each iteration on your word_list. Then, use str.replace and its optional argument count to modify the copy of ORIGINAL and avoid the duplicated letter problem by removing the matched letter:

for word in word_list:
    temp_original = ORIGINAL  # Create a copy of ORIGINAL
    for i in range(len(word)):
        if word[i] in temp_original:  # Lookup the copy of ORIGINAL
            ...
            temp_original = temp_original.replace(word[i], "", 1)  # Remove the seen letter from your copy of ORIGINAL
        ...

Resulting code:

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

Output:

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

CodePudding user response:

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