Im very new on python, actually, Im not even a programer, Im a doctor :), and as a way to practice I decided to wright my hangman version. After some research I couldnt find any way to use the module "random" to return a word with an especific length. As a solution, I wrote a routine in which it trys a random word till it found the right lenght. It worked for the game, but Im sure its a bad solution and of course it affects the performance. So, may someone give me a better solution? Thanks.
There is my code:
import random
def get_palavra():
palavras_testadas = 0
num_letras = int(input("Choose the number of letters: "))
while True:
try:
palavra = random.choice(open("wordlist.txt").read().split())
escolhida = palavra
teste = len(list(palavra))
if teste == num_letras:
return escolhida
else:
palavras_testadas += 1
if palavras_testadas == 100: # in large wordlists this number must be higher
print("Unfortunatly theres is no words with {} letters...".format(num_letras))
break
else:
continue
except ValueError:
pass
forca = get_palavra()
print(forca)
You may
\n
char fom each line, because it count as a characterchoice
on lines that hasn't the good length, filter first to keep the possible onesgood_len_lines
list has no element you directly know you can stop, no need to do a hundred picksdef get_palavra():
with open("wordlist.txt") as fic: # 1.
lines = [line.rstrip() for line in fic.readlines()] # 2.
num_letras = int(input("Choose the number of letters: "))
good_len_lines = [line for line in lines if len(line) == num_letras] # 3.
if not good_len_lines: # 4.
print("Unfortunatly theres is no words with {} letters...".format(num_letras))
return None
return random.choice(good_len_lines) # 5.