Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick a Random Word On a Single Line In Python?

How would I pick a single line and pick all the words on that line and then print them to the screen using a set. This is what I have so far:

import random

test = ['''
line 1
line 2
line 3
line 4
line 5
line 6
''']
print (random.choice(test))
like image 717
Noah R Avatar asked Jul 16 '26 12:07

Noah R


2 Answers

I think this does exactly what you're asking:

print random.choice(test[0].split('\n'))
line 5

I have a feeling you're looking to do a little more than that, though.

like image 137
JBWhitmore Avatar answered Jul 19 '26 03:07

JBWhitmore


I suspect you want to pick them randomly without replacement; if all you do is pick words randomly, with something like

do until set empty
   pick a random word and print it

it would (a) not terminate, and (b) repeat words on average every 1/n times for n words.

It would be tempting to use a Python set, but inconveniently there's no obvious way to pick a random item from the set since it's not ordered. (You might make a case that set#pop will work since it takes the arbitrary next item, but if I were grading I wouldn't give that full credit.) On the other hand, the description says a set.

So I'd do something like this:

First put the items into a list. Note that what you have puts one string with 10 lines into the list,, that is your list has length 1. I'd bet you're better off initializing like

words = [ "test 1","test 2" # and so on
]

Next, select your items using choice as

word = random.choice(words)

Print it

print word

and remove it from the list

words.remove(word)

Put that in a loop that continues until you run out of words. You get something like:

>>> import random
>>> words = ['a', 'b', 'c' ]
>>> while len(words) > 0:
...    word = random.choice(words)
...    print word
...    words.remove(word)
... 
b
a
c

gnibbler points out that you could also have

import random
words = [ ... ]
shuf = random.shuffle(words)
for i in shuf: 
   print i

but that doesn't treat the list as a set; it depends on there being an implicit order set by shuffle.

like image 29
Charlie Martin Avatar answered Jul 19 '26 01:07

Charlie Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!