[Tutor] Re: problem writing random_word function
Karl Pflästerer)
sigurd at 12move.de
Mon Jul 19 20:11:16 CEST 2004
On 19 Jul 2004, Matt Smith <- smith-matt at tiscali.co.uk wrote:
> Thanks Lloyd,
> I've rewritten the function as below and everything seems to work
> correctly.
> def random_word(word_length):
> """Returns a random word of length word_length"""
> import random
> f = open("hangman_words.txt","r")
> word_list = []
> while 1:
> word = f.readline()
> word = word.strip()
> if word == "":
> break
> elif len(word) == word_length:
> word_list = word_list + [word]
> f.close()
> return word_list[random.randint(0,(len(word_list)-1))]
That function works but you could improve it a bit.
First: don't import modules in functions. That may lead to dead locks.
Second: you could write the above shorter and more pythonlike without
the wile loop.
Third: You mustn't forget that there may be no mathing word in your
file.
Fourth: don't hardwire the name of the file.
import random
def random_word (length, data="hangman_words.txt"):
f = file(data)
wordlist = [word for word in f if len(word.strip()) == length]
f.close()
if len(wordlist) > 0:
return wordlist[random.randrange(0, len(wordlist))].strip()
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list