1

In my program, the user inputs a secret word that another person is to guess (hangman). The letters are then put into a list. I am trying to make a loop that checks if there are several equal letters in the list, and remove them if there is. This I have managed. The problem is that this loop also removes other characters that are not ment to be removed.

word = []

for i in range(int(len(secret_word)) - 1):
    if word[l] == word[q]:
        word.pop(l)
        q += 1
        if q > int(len(word)):
            break
    else:
        l +=1

Using the word "secret" and then printing the list, the output I get is

['s', 'c', 'e', 't']

It has removed the e, but unfortunately the r is also removed. Also, this loop doesn't remove a third equal letter. Using "secretive" the output is

['s', 'c', 'e', 'i', 'e']

Here, removing one of the e's, but also r, t and v

Frayal
  • 2,117
  • 11
  • 17
vault
  • 124
  • 1
  • 9

2 Answers2

0
word = 'secretblahblahset'
result = ''

for c in word:
  if not c in result:
    result += c 

print(result)
Tohmaxxx
  • 423
  • 2
  • 9
0

Your example code is missing a number of features such as the initialization of q and l. And I suspect you must have an outer loop that you're not showing us, otherwise the example doesn't make a lot of sense (in the example as given word is just an empty list).

If you want all the unique letters in a string you can do so easily with set():

unique_letters = set(secret_word)

However, that will not preserve order. I don't know for your case if you even need to preserve order. But if you wanted to there are many ways to do so, often still involving set() but not necessarily. Here's one way:

unique_letters = []
seen = set()
for let in secret_word:
    if let in seen:
        continue

    unique_letters.append(let)
    seen.add(let)

Another way, as a one-liner, might be something like:

unique_letters = sorted(set(secret_word), key=secret_word.index)

Those are just a few examples. There are many ways to do this. I'm sorry I can't say exactly what's wrong with you code. The example is missing too much context. But you're probably overcomplicating the problem.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63