Python, random

Started by
10 comments, last by Zahlman 16 years, 1 month ago

Upon further reflection you don't even need to remove anything. random.shuffle() take care of it...if you do a regular for loop there's no chance it will accidentally "back up" and repeat the same word. As usual, there are myriad different ways of doing the same thing.

Most of my Python self-education has been done by reading the docs (they are online at python.org but also bundled in a help .chm file in my Windows install) and then testing things out in the command-line interpreter. Based on something I read in the manual, I make a prediction about what a line of code should do. I then type it into the interpreter and see if I was right or wrong. I repeat with varying values, types, etc. to see if I fully understand.
Advertisement
Yeah, that would be an example of confusing two approaches to fixing the problem.

When you random.shuffle() the list, it's already shuffled. You can just go through and print each thing, and there will be one of each, in a random order. That's what shuffle() does.

If you want to shuffle by yourself, the idea is to, each time, randomly select one of the remaining things, and then remove it from the list. As it happens, we have a direct way to select something from a list: random.choice(). We don't need to generate an index and then index into the list.

hat = ['a', 'boy', 'came', 'down', 'expecting', 'fly', 'girls', 'here']while hat: # This implicitly means "while the list is not empty".  word = random.choice(hat) # Randomly pull a word out of the hat,  print word # display it,  hat.remove(word) # and actually *pull it out* of the hat. ;)

This topic is closed to new replies.

Advertisement