[Tutor] Re: problem writing random_word function (original) (raw)
Nithya Soundararajan s.varun at gmail.com
Mon Jul 19 20:32:18 CEST 2004
- Previous message: [Tutor] Re: problem writing random_word function
- Next message: [Tutor] Re: Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Hi, a better way for loading the file could be to convert it to pickle form and then use it.(May be helpful only if you wanna load it with two lines. ;-) ). import pickle f=open(yourfile,"r") word_list=pickle.dump(f) (this will work only if you hv already converted the hangman_words.txt to pickle format, it will be easier for you and your code will look more geekier. Pour your comments -Varun
On Mon, 19 Jul 2004 20:11:16 +0200, Karl Pflästerer) <sigurd at 12move.de> wrote:
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 randomword (length, data="hangmanwords.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
Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor
- Previous message: [Tutor] Re: problem writing random_word function
- Next message: [Tutor] Re: Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]