0

I just finished learning how to do lists in python from the book,Python Programming for the Absolute Beginner, and came across a challenge asking to list out words randomly without repeating them. I have been trying to do it since the book doesn't gives you the answer to it. So far this is my code:

WORDS = ("YOU","ARE","WHO","THINK")
for word in WORDS:
    newword=random.choice(WORDS)
    while newword==word is False:
          newword=random.choice(WORDS)
          word=newword
          print(word)

As obvious as it seems, the code didn't work out as the words repeat in lists.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Luke Wee
  • 3
  • 3
  • Remove the item from the list when you random.choice it? (for instance by gettings its index and using 'del' function. I'm sure there are plenty of other faster ways with python.. ) – trainoasis Sep 03 '15 at 06:13
  • Assuming you can modify the list, use `random.shuffle(words)` – Pynchia Sep 03 '15 at 06:17
  • @trainoasis You mean by creating a new list and random.choice from that list then del the words? Worth a try.thanks – Luke Wee Sep 03 '15 at 06:18
  • @LukeWee yeah. I added an even better solution probably, check below – trainoasis Sep 03 '15 at 06:33

2 Answers2

2

You could use shuffle with a list instead of a tuple.

import random
lst = ['WHO','YOU','THINK','ARE']
random.shuffle(lst)
for x in lst:
   print x

See this Q/A here also. To convert a tuple to list: Q/A

The whole code if you insist on having a tuple:

import random
tuple = ('WHO','YOU','THINK','ARE')
lst = list(tuple)
random.shuffle(lst)
for x in lst:
   print x
Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
0

Add the printed word to a different array (e.g. 'usedwords') and loop through that array every time before you print another word.
Thats not perfomant but its a small list... so it should work just fine
(no code example, it should be in a beginners range to do that)

Minzkraut
  • 2,149
  • 25
  • 31