[Tutor] Re: problem writing random_word function (original) (raw)
Karl Pflästerer) sigurd at 12move.de
Mon Jul 19 20:11:16 CEST 2004
- Previous message: [Tutor] Re: problem writing random_word function
- Next message: [Tutor] Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 randomword(wordlength): """Returns a random word of length wordlength""" import random f = open("hangmanwords.txt","r") wordlist = [] while 1: word = f.readline() word = word.strip() if word == "": break elif len(word) == wordlength: wordlist = wordlist + [word] f.close() return wordlist[random.randint(0,(len(wordlist)-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
- Previous message: [Tutor] Re: problem writing random_word function
- Next message: [Tutor] Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]