zed
zed

Reputation: 1

Selecting random letters for Hangman

flink = open("C:/python27/2of12inf.txt", "rU") 
words = [ ]            
for eachline in flink :      
    words += [eachline.strip()]
flink.close()                
print "%d words read" % len(words)
return words

how do I select 6 random letters from this list?

Upvotes: 0

Views: 354

Answers (3)

FireSwarm
FireSwarm

Reputation: 23

This function returns a random string from the passed list of strings.

 def getRandomWord(wordList):
     wordIndex = random.randint(0, len(wordList) - 1)
     return wordList[wordIndex]

this function gets a random word using the def above.

 secretword = Randomword(hangmanwords)

Upvotes: 0

Drover
Drover

Reputation: 116

random.sample is a little cleaner

>>>words = "one two three four five six seven eight nine ten".split()

>>>import random

>>>random.sample(words, 6)
['six', 'seven', 'eight', 'nine', 'three', 'ten']

>>>random.sample(words, 6)
['three', 'five', 'four', 'six', 'one', 'ten']

>>>random.sample(words, 6)
['ten', 'five', 'two', 'nine', 'seven', 'eight']

Upvotes: 0

Claudiu
Claudiu

Reputation: 229421

The simplest way I can think of is to randomize the entire list and take as many elements as you need:

>>> words = "one two three four five six seven eight nine ten".split()
>>> import random
>>> random.shuffle(words)
>>> words[:6]
['two', 'five', 'six', 'seven', 'four', 'one']
>>> random.shuffle(words)
>>> words[:6]
['five', 'seven', 'nine', 'three', 'four', 'eight']

Upvotes: 2

Related Questions