There are a few problems with your code as it stands. Firstly, this line:
wordList =["antidisestablishmentarianism"]
doesn't do what you think - it actually creates a list containing the single item "antidisestablishmentarianism"
. To convert a string into a list of characters, you can use list()
- and since you've already have the variable word
, there's no need to type the word in again.
On a side note, wordList
isn't a very good variable name. Apart from the fact that it uses camelCase rather than the more pythonic underscore_separated style, what you actually want here is a list of the characters in the word.
So, that line can be replaced with:
characters = list(word)
Moving on ... this line:
lengthWord = len(word)
is redundant - you only reference lengthWord
once in your code, so you might as well just replace that reference with len(word)
where you use it.
Your line:
usedValues=[position]
also isn't doing what you think: it's replacing usedValues
entirely, with a list containing only the latest position in your loop. To append a value to a list, use list.append()
:
used_positions.append(position)
(I've given the variable a more accurate name). Your next problem is this block:
for ch in wordList:
wordList.remove([usedValues])
First of all, you really want to check each of the positions you've previously stored, not each of the characters in the word. Your use of list.remove()
is also wrong: you can't give a list of values to remove like that, but anyway list.remove()
will remove the first instance of a value from a list, and what you want to do is remove the item at a particular position, which is what list.pop()
is for:
for position in sorted(used_positions, reverse=True):
characters.pop(position)
We're using a copy of used_positions
sorted in reverse so that when we remove an item, the remaining positions in used_positions
don't slide out of alignment with what's left of characters
[*].
Your final problem is the last line:
print("The remaining letters are",WordList, sep='')
If you want to print the contents of a list separated by ''
, this isn't the way to do it. Instead, you need str.join()
:
print("The remaining letters are", "".join(characters))
Putting all of those changes into practice, and tidying up a little, we end up with:
import random
word = "antidisestablishmentarianism"
characters = list(word)
print("The Word is:", word, "\n")
used_positions = []
for i in range(5):
position = random.randrange(0, len(word))
print("word[",position, "]\t", word[position])
used_positions.append(position)
for position in sorted(used_positions, reverse=True):
characters.pop(position)
print("The remaining letters are", "".join(characters))
[*] In fact, this throws up another problem: what if your code chooses the same position twice? I'll leave you to think about that one.